Commit 64d8089f by 苗权威

2.14

parent 73a61fb7
This source diff could not be displayed because it is too large. You can view the blob instead.
package ai.qiwu.tmall.spirit.controller;
import ai.qiwu.tmall.spirit.po.CookieUpdate;
import ai.qiwu.tmall.spirit.service.SpiritService;
import ai.qiwu.tmall.spirit.spirit.SpiritAudioUpload;
import com.alibaba.da.coin.ide.spi.standard.ResultModel;
......@@ -128,6 +129,14 @@ public class SpiritController {
return "success";
}
@PostMapping("update")
public void updateCookie(@RequestBody CookieUpdate data) {
SpiritAudioUpload.token = data.getToken();
SpiritAudioUpload.cookie = data.getToken();
SpiritAudioUpload.csrfToken = data.getCsrToken();
System.out.println("token:"+SpiritAudioUpload.token);
}
@GetMapping("/del")
public void del(String filepath, Long skillId) {
spiritAudioUpload.deleteAudio(filepath, skillId);
......
package ai.qiwu.tmall.spirit.po;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class CookieUpdate {
private String cookie;
private String token;
private String csrToken;
}
......@@ -50,9 +50,9 @@ public class SpiritAudioUpload {
@Value("${csvDicForBotChange}")
private String csvDicForBotChange;
private volatile String cookie = "dnk=tb13503054; t=f7d06d2e248fc07aa83289307aa4a764; tracknick=tb13503054; enc=nxqSx7%2Bh17LC3JcQmuWryBEA3g%2BBQXPR5Yjzs%2FgXE1NL3ugqfFWtSRIPXXeSIBbLjdMyJYXMRxPVk65RKEod0Q%3D%3D; _tb_token_=e373f335bb333; cookie2=144d7e656949f09b0f5432fa8fccc24a; cna=J1ApEybNe0UCAXQeRp7gOjrr; UM_distinctid=16ec8f74975752-01cfeaef5bdb6d-2393f61-e1000-16ec8f74976888; uc1=existShop=false&cookie14=UoTbmEhZbnUtCA%3D%3D&cart_m=0&cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D&pas=0&cookie15=UIHiLt3xD8xYTw%3D%3D&cookie21=VFC%2FuZ9ainBZ&tag=8&lng=zh_CN; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=53964595; accountId=52463; accountType=TB; confirmProtocolVersion=1; ctoken=N6keiCTfw7DOtJ76KUHLnsoG; token=xe4nPWfClphv5+4SD5I8ocz/Km7t9hyNdXLKagm/jAk=; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnP_VI-r_CiXhigB24HUxJr2EAADqCPIuCrvinUugwUDdbQvx-ay8eof1QwEUukNH_zunLzRWU6aVqoN1ul2_uxG8FPkfVbnawQ6PePgZ2cUELrwNbcWjnHP0ZLLi24iOmdBLx_YbBF0QP4Okdq_EwdFH8aX3a0LQBQXzsSHl8nMpEIjz6-xe5ZAOYqvqBfOIoK49xcaVf3GDp7_k8DeYlqFyB9L0W8d1pjh6MN2nkh9PVoGsrZZ2r0dLBFv6of2yqocpMBv1rLwQS4dPwzlAFYnQ14QwsAv7PK1fElkRid4nhbOzs8YxwZYd0GBUOlKO1kukxu5n2JTcfbsFGD_uFc19GNnO2eH2oM6wQo2iMaeCuWHmDSs9AwHkK4ZZ7p7lNHLSjvSRNA2HH3XIPRRJcgc5w3H2626pQ8yvprnetQ-JzzoxsAM17tDZLIoUlhNZQrrcWW4RYz3cI5E6J5z-jcGKRtD4r0dTpSwUVsYp6a6-PNU71NynGTk1jzilhmwCXogo4K73iFIx0x7BJroamqlfe00a8BRFdpAqqvpcEk243NL8axaQacUFzhSFvJ8M91KPlH-PTMfQysaOx4GT9raVhqsJcePK22hH7PYG6PoMlK7ePw_wriHaHGB2KVPZbFW9pj20VH4UrcRUclVis0kQ5cnbCo3zIkK7ZAhFenMHe-XBf-E9RJ1qKf2Se8CJSzAjeuUb2xrF-qd8V1AqZ245Lb9scttIfohdjLGAF6Ou-Jw-8fCy1J4D_8P1VqLjz5vnwp0kkn3TZyTPC7-AfXkYOgBkd97LugAYpbZu0TY3_nYGUQVdNNlKLRcveVr1inGfDknqQXJZMs694Cr1swf_vX-ttoz3Sd4R0Ctyu2KbeldstqdZoU2jvTKMCNAXcyzwNyKFO_NkdKPH8ks_Yj6mQmz2Ow8f-l8eSSc5hzkcNBfNhZb1p26mFYAyVA5D1tFOBbMBybiLoYZXiQH7cm7YPow2yQbMtEz5mpKNisVV8rLAO9DGI88vEgJRyKvoiEqBzPVhfEiguuYa-XXMA2xXGnDBp7zwK3P2kaiJ63uvfbNhEQhve4reBfH2ojRJG4RXODXO_O9_s6lZy0yRUneBzY5S38kK2AyWl5gWOwKDWCZWHqxcYOy2qmcxYCAJfMV_We8WaUJjlP6eTN8P5rS0WXjCdQ3p7yBOXKdkEYXm6ysuoNxxoGB9QznmWJsaMxtRG00Wz0SCdI13TzQ1lfSbBVvILYw1BfG4qlvnxbO4r-tDR4eZClg3t_C6eHdWowgYy4G3Nnln9asw8IW4MhNjZLEekL7IVDtzdDlLf3nTANLIIckJMrQ-JCWwcb-Igwh7nvussBt0C8trJXACcWwct3M4VVUgOz53wz-pHHO-i2wK8eCarxtnwmAnppIbpHiePF5HZA5lIrFucbbWg6bCARAKfBgOgpNoD-Er52UKvjD9qu-R1Q3sggnEsqk_8SGIlx-pfPSaq9Y6A42ilqHZv2UyRUU5GmUO3i7JTNjzuvx22jBV0gl3vFg7vYdtuzAKj_8OJy5hF_iYy1RFj05IsGbwmUOC6p5xi-rQYgK0OTybeBovfsxxrApymMsTlLTVDvtSbSfe5b8piSACkGk73E-1SgE5X7NhdBVVlqhwM-TiNlVVzY5AyPWB0pc2U3_GFIZ56mtboU129YtpMhJGgm4YZ2znJV7sSU8AbXy8TKcvPUohUgf_5koZzByOiKrIoho2iiLkpqK5DzNrzk2H3loI8SWAydCzJg-7dCR2_s_3wMFXXWZNCpHadVgXpx1Nwd0RRN4eflamebFKlsPTx70naCDSdReR6oGjHliwBELuGb_tkKOYwfMNXEzCCHWkASYtFmHf0u3YK8VUyK9fgWnSh7bkrlh6zoOU1izX1fwDexI7CF9BE0LxqkaLC_nn295kZeIYlQO6Pk9-EP01Wjdvwqc9emWahrfOEMVEU6wdV_gO4_sHel8gAamUaWVRua7-Kl1u6igUm_hNwptHnBisAtCNtqV0WDZJ-oirGMpFqt4aghE9Wy9XiGwOJ3_I1wunKP2ddnxfSayg3iLVlH9RCPRxNR2atC9sQ3Nv__8QCa020V2EFU1LpwVU0lC5mxUACm8yuTzfa-aeiz7Qj2HJHTVLUI6yttmO66AlfAGfUPE63Z7Yseps2uReX6SRsKEDP5px59ufi5jrWpeGZ57Uh9oRJZv9fBZR7Q-Ajy0MJqUZEWYIKkpQ6D2ObDh0_nHxjvbBb4ZrQMQit5PehnXgoIwAExjk3L3y_3dLP_-lurBaV5LSMIiAj0B3IQ==; CNZZDATA1261708326=42777204-1575329673-https%253A%252F%252Fwww.aligenie.com%252F%7C1580998884; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20common%2F%E8%8E%B7%E5%8F%96%20oss%20token%7Cp; isg=BFpa7Yf70Gmj-18cC8krhnz9qwB8i95lub9gaWTZ0u1Z1-4RTxqDdaxhp6PLB1b9";
private volatile String token = "xe4nPWfClphv5+4SD5I8ocz/Km7t9hyNdXLKagm/jAk=";
private volatile String csrfToken = "N6keiCTfw7DOtJ76KUHLnsoG";
public static volatile String cookie = "dnk=tb13503054; t=f7d06d2e248fc07aa83289307aa4a764; tracknick=tb13503054; enc=nxqSx7%2Bh17LC3JcQmuWryBEA3g%2BBQXPR5Yjzs%2FgXE1NL3ugqfFWtSRIPXXeSIBbLjdMyJYXMRxPVk65RKEod0Q%3D%3D; _tb_token_=e373f335bb333; cookie2=144d7e656949f09b0f5432fa8fccc24a; cna=J1ApEybNe0UCAXQeRp7gOjrr; UM_distinctid=16ec8f74975752-01cfeaef5bdb6d-2393f61-e1000-16ec8f74976888; uc1=existShop=false&cookie14=UoTbmEhZbnUtCA%3D%3D&cart_m=0&cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D&pas=0&cookie15=UIHiLt3xD8xYTw%3D%3D&cookie21=VFC%2FuZ9ainBZ&tag=8&lng=zh_CN; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=53964595; accountType=TB; confirmProtocolVersion=1; ctoken=H460GyYx-d_1r1t5zC0LhPP7; accountId=52463; token=zjt4ePdjCjC0+y8U0tLxO5oJUpZH3daOn0fd0pQPSnc=; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnD7BTdYqw-7V1GkCKaIWHFLLeVSSS9jC13moc0W1SH9GDhePuBh5f9kfoSaqb6ChWf2z3kPbuCXMqsQpt0mvozK3CjPA2OnZRJzYc3QAIZaD8oDUq67fFPm4DGnaQFab2jVgz9JVx5qZt9SoQEpna51P1ygHPTjj6Urx7ohFYxYfw-IZhgsuRReO258QICdLaMjDOPHv1eYb7fde6sbTgcrU23_ECAu5h_XKmEzbS8HJ30xr6SX7EMC8H0WkXPByYUtDcYt9hOyhdw35xbZrz_KEhwuyVfG3Dn_qPIsrWBPiGBG56iFRD-bQKGpNGDIzOvJRrBdjmeoYGT-WmuRG-RAO-pwxrAbJeZ4watqlg8HnZF3VnDgtiYxE3FCPPSXUTnzHhbJr6I-JZ4X-Y-rI1EFhaQx_vAPImlBSOCO1IdXEl9--pe2jDORiNc3sVeZ_HvWx2LU3A9_nSOdvcNV2tfyvPDSR7DOIQjcBoxwnA9hZF0rKxLHTlLf6U3Q5MzRiE3izczdM9CuSfXA9QbDtSybB9DjaOGP-JvkBdDbI3C4auNT5H_-XfcrIlXI9Es8MV35V9OEdFSVdTZ0H2hydc4IMFcXk5cPxWcHSFsYcca968nkfzeL2LGs7uyBm9XOLs3K7whXrt0OAMIxcRQ91Yun7jtp-7KXfpdyGdjkY9cfgGt9GsuQDCKLU0xaKcwn3qju74OhKZmWHlBH0YBxTtlLBe6kCSzkQ0g9KxZTpPqN8UB0cIyma4yNH8oVGxjP3p8v5OwzRZJggMITh86LjDUuf0AXRH9Wczu_0ZFA3ubGeCISJCb6axoYIayC_QIPsJWlUvCcuuepJLsHvB178iyoRpUvafcfrt2l8LETrnEmBwtBInyTduP4UIGOmT79t4t-HnwAuQbfP0LVyX5-3vD_g_SwXgFiMtTTHSjnKOm7XqCfcsPA_QFRYwmLy4x23d6YHGL_OdenBNtIofnUKB8dUaDTdnAXG9n1zXmNVi5qh3kvK2w5D6oWkS3ck2nn01agnKqBM4ynbxo81xdAmpiIMIZeUh8rXEH0iCTyydTPAL-CYTMasdMkROYdBSaVVx3r2W5rmVF1QIjr_LjBY7GJM_3yl7h30WHPIfv5sVo4HdaV-ZtgjvE-pdSuhueeI9vBrYTlWowcVBYSguuY4SS8VQWGSQNd8qA1pllGlcLmplrCZgAtFKqqJoyxmNLDq4P_8QfeoTDiYVkImx3pxVmGdXwQm4krsxCos7jbw9BX1oukl2abhtU_zgKjoVveu4kTxsFUUSoxFqHrxl5pfi_epBOamnnUaA2XpAXe9cbaNLwLy0k81jb8fqQK9ITIzgu5n--pPC-eEoWi6nD3DmmWZ4eOWEh06xImnwBHM4cPwLiun_J8FpbykIo7-wFcEyQsEZYsrUzvfad5ATrXoLqp82qCagUO1vuUkVsSMWD1llZXD4AhiG8AIdDBy114Zc9Y8QTT27sPsANCCRNnu-VOdXCY-3O3BwgKbgXIVtQLgc-3_dnNBRkgiUn5MNZEwTjyQPfsu5LBCFC64Z502ms2HtgS7h-mv9oLcrIhAo_V4FG6DsNN6qbvmhE3Ww5PFQ0ZlB-tYLf_-lchNrQQsonnXO7pUuvha9eNTF23S98uqHi7pmQ4viRNCojkZr9shfz6YMcAOwdeM_6CRwaG3_ZxWlZB1EyxYdYXx7aYTGoLKmcFlh1Tntjw5PCOkAQWKwWVfpU4Xr5tf8OShheRTVZyPjopQzMByz9HT07voshh_CGMWrQ75pOQ4KmR-vSa4FNsb_vfstjcGm7dptPOYgvLkkhpnbMgsk4qTkwO-kK6E6hCCcRntVMIub_Oy0jvEuCtC6MoauzN2oWMmm33XXOVnxZZZv_lph292z29zGjwv3i40XG9zNfQANJjMQ21II7cei8QAoxa8d-pCeZeiQfS4VFavWxS65xcYQSz2Gg0dxd_pN0yBVyCqwRKZ1iE1QkWWipdJJOBHE42cPkMUG2s2w0wXtx_0HuWeJdea-xoReB1O1l0Zyr_nUXZUJiZulOgcVs-ZnvRwflYQuWMva-847t3nmzMQcrVh6zAahcbO87kvqSzXW16pRe08nVpyyIy4ahEZE95w3yCygTrzmrPKEAAmIJlySA7y_C8X51q-qoQKgs0ajbKndIBNavYmtR2xbHXWF18hZff0k2hdsuP0km40fB1uBltd1jE6LqWaQ6_eO0zPhMjwSRYlfVyCdba3t7ikqKU_P_cwuPuvXFePY6KRf0pZuIj9lY6n6YlryK74E67A9XGxcZ_78dzGNA==; CNZZDATA1261708326=42777204-1575329673-https%253A%252F%252Fwww.aligenie.com%252F%7C1581151796; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20skill%2F%E6%9F%A5%E8%AF%A2%E6%8A%80%E8%83%BD%7Cp; isg=BP__k6UqnQggYZrPHnaWBXFqjtOJ5FOGn_kryZHPyq7joBcinLS61zH24nBe-Cv-";
public static volatile String token = "zjt4ePdjCjC0+y8U0tLxO5oJUpZH3daOn0fd0pQPSnc=";
public static volatile String csrfToken = "H460GyYx-d_1r1t5zC0LhPP7";
public void updateCookie(String cookie) {
this.cookie = cookie;
......
......@@ -7,6 +7,7 @@ import ai.qiwu.com.tts_service.service.Initialize;
import ai.qiwu.com.tts_service.service.LieHuSchedule;
import ai.qiwu.com.tts_service.service.TTService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
......@@ -240,4 +241,12 @@ public class TTSController {
// ttService.apiAudioGet(type, path, response, request);
ttService.apiAudioGetNoRange(type, path, response);
}
@PostMapping("/api/update/xiaoai")
public void xiaoaiCallbackUpdate(String callbackUrl, String secret) {
if ("mqwXiaoAi.".equals(secret) && StringUtils.isNotBlank(callbackUrl) && callbackUrl.contains("xiaoai/audio/play")) {
Initialize.audioUrl = callbackUrl;
log.warn("小爱回调地址更新:"+callbackUrl);
}
}
}
......@@ -21,6 +21,8 @@ import java.util.*;
@Component
@Slf4j
public class Initialize implements InitializingBean {
public static volatile String audioUrl = Config.getProperty("audioCallBack","https://didi-gz4.jiaoyou365.com/xiaoai/audio/play?userId=");
/**
* 默认person
*/
......
......@@ -89,9 +89,6 @@ public class TTService {
this.stringRedisTemplate = stringRedisTemplate;
}
@Value("${audioUrl}")
private String audioUrl;
// /**
// * 退出请求的处理/返回TTS_test.mp3文件的下载链接
// * @param request
......@@ -2203,10 +2200,20 @@ public class TTService {
public void apiAudioGetNoRange(String type, String path, HttpServletResponse response) {
boolean xiaoAi = StringUtils.isNotBlank(type);
if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type);
OkHttp3Utils.backPostAsync(Initialize.audioUrl+type);
}
int count = 0;
log.info("apiAudioGetNoRange: path->"+path);
// log.info("apiAudioGetNoRange: path->"+path);
if (!path.startsWith("a")) {
if (Files.exists(Paths.get(path))) {
TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
return;
} else {
log.warn("path start with a but not exist:"+path);
return;
}
}
path = path.substring(1);
Path pt = Paths.get(path);
boolean fileExist;
while (!(fileExist=Files.exists(pt)) && count < 15) {
......@@ -2240,6 +2247,7 @@ public class TTService {
else if (StringUtils.isBlank(botName)) {
return "null";
}
boolean allExist = true;
final List<Future<ResponseCodeWithData>> futures = new ArrayList<>();
final List<String> file_ls = new ArrayList<>();
String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString();
......@@ -2321,6 +2329,7 @@ public class TTService {
}
if (!TTSUtils.doesFileExist(filepath)) {
allExist = false;
//log.info("不存在地址:{},text:{}, botname:{}, tone:{}, person:{}",filepath, text, botName, tone, person);
final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text,
person, tone, botName, true, volume, speed, pitch);
......@@ -2370,29 +2379,37 @@ public class TTService {
// 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3,
// 成功则构建请求get_audio接口的请求url,包括参数信息,返回该url
String temp;
if (file_ls.size() == 1) {
final String tmp_audio_name = file_ls.get(0);
POOL.submit(() -> task(futures, tmp_audio_name, file_ls, null));
if (!allExist) {
POOL.submit(() -> task(futures, tmp_audio_name, file_ls));
}
String result;
try {
return URLEncoder.encode(tmp_audio_name, "UTF-8");
result = URLEncoder.encode(tmp_audio_name, "UTF-8");
} catch (Exception e) {
return URLEncoder.encode(tmp_audio_name);
log.warn("apiAudio URLEncoder fail");
result = URLEncoder.encode(tmp_audio_name);
}
if (allExist) return result;
else return "a"+result;
} else {
temp = TTSUtils.pythonlistToStr(file_ls);
String temp = TTSUtils.pythonlistToStr(file_ls);
// String dirs = String.format("[%s,xiaoai]", botName);
final String folder = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai"}, File.separator);
final String tmp_audio_name = new StringBuilder(folder).append(File.separator).append(temp).toString();
POOL.submit(() -> task(futures, tmp_audio_name, file_ls, folder));
final String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai",temp}, File.separator);
if (!TTSUtils.doesFileExist(tmp_audio_name)) {
POOL.submit(() -> task(futures, tmp_audio_name, file_ls));
return "a"+tmp_audio_name;
} else {
return tmp_audio_name;
}
}
}
return "null";
}
private void task(List<Future<ResponseCodeWithData>> futures, String tmp_audio_name,
List<String> file_ls, String folder) {
List<String> file_ls) {
try {
// 阻塞等待mp3文件生成成功
//log.info("196:file list:{}", file_ls);
......@@ -2406,6 +2423,10 @@ public class TTService {
}
else if (data.getCode() != 200) {
if (data.getCode() == 8) {
if (file_ls.size() == 1) {
log.info("音箱,单个,不存在,竞争:"+tmp_audio_name);
return;
}
log.info("task:出现竞争情况->"+data.getRes());
if (data.getRes() != null) {
int count = 0;
......@@ -2416,6 +2437,7 @@ public class TTService {
++count;
}
if (count == 20 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes()))) {
log.info("task:等待10仍未等到对方完成该任务->"+data.getRes());
return;
}
}
......@@ -2425,16 +2447,16 @@ public class TTService {
return;
}
} catch (Exception e) {
log.error("tts_ls获取结果出错:{}", ExceptionUtils.getStackTrace(e));
log.error("task 获取结果出错:{}", ExceptionUtils.getStackTrace(e));
return;
}
}
if (folder != null && !TTSUtils.doesFileExist(tmp_audio_name)) {
if (!TTSUtils.doesFileExist(tmp_audio_name)) {
boolean addSuccess = false;
try {
if ((addSuccess=Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
.setIfAbsent(tmp_audio_name, "1", 20, TimeUnit.SECONDS)))) {
TTSUtils.makedir(folder);
Files.createDirectories(Paths.get(tmp_audio_name.substring(0, tmp_audio_name.lastIndexOf(File.separator))));
TTSUtils.combineMp3File(file_ls, tmp_audio_name);
if (!TTSUtils.doesFileExist(tmp_audio_name)) {
log.error("小爱平台的请求,聚合mp3文件失败");
......
......@@ -54,6 +54,7 @@ public interface Constants {
String COLLECT_IMAGE_ID = "collectImage";
String COLLECT_TEXT_ID = "collectText";
String BACK_TRACE = "trace";
String NEXT_PAGE_INDEX = "comCnt";
String PRE_CATEGORY = "categ";
String PRE_FUNNY_IMG = "funny";
......@@ -112,10 +113,12 @@ public interface Constants {
String WELCOME_SMART_FORMAT = "欢迎来到晓悟智能故事。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线了%s,你可以说打开%s。或者说,推荐其它作品。";
String WELCOME_SMART_FORMAT_AI = "欢迎来到晓悟智能故事。推荐我们新上线的%s,你可以说打开%s。或者说,推荐其它作品。";
String SKILL_SMART = "智能故事";
String XIAOWU_SKILL_SMART = "晓悟智能故事";
// 与剧情人物自由对话,带您体验不同的人生和情怀。
String WELCOME_NOVEL = "欢迎来到晓悟智能小说。向您推荐新上线的妖刀异闻录,您可以说打开妖刀异闻录。或者说,推荐其它作品。";
String WELCOME_NOVEL_FORMAT = "欢迎来到晓悟智能小说。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL_NOVEL = "智能小说";
String XIAOWU_SKILL_NOVEL = "晓悟智能小说";
String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我";
String SKILL_LITERATURE = "互动文艺";
String WELCOME_STORY = "小朋友你好,欢迎来到交互故事,你可以对我说有什么好玩的吗";
......@@ -130,7 +133,9 @@ public interface Constants {
String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_NOVEL = "后续有更多作品上线,欢迎常来访问智能小说。"; // smart novel
String XIAOWU_END_BYE_NOVEL = "后续有更多作品上线,欢迎常来访问晓悟智能小说。"; // smart novel
String END_BYE_STORY = "智能故事后续会有更多作品上线,欢迎常来"; // smart story
String XIAOWU_END_BYE_STORY = "晓悟智能故事后续会有更多作品上线,欢迎常来"; // smart story
String END_BYE_JIAOYOU = "交游天下后续会有更多作品上线,欢迎常来";
String END_BYE_DEFAULT = "后续会有更多作品上线,欢迎常来我们的技能";
String END_BYE_Adult = "再见啦,记得下次再来玩哦";
......@@ -168,10 +173,12 @@ public interface Constants {
interface XIAOWU_API {
String BASIC_PREFIX = "Basic ";
String BEARER = "Bearer ";
String CAPTCHA_SMS = "https://account-center-test.chewrobot.com/api/captcha/sms";
//https://account-center-test.chewrobot.com/api/captcha/sms
String CAPTCHA_SMS = "https://account-center-test.chewrobot.com/api/sdk/captcha/sms";
String REFRESH_TOKEN = "https://account-center-test.chewrobot.com/api/sdk/token";
String SDK_TOKEN = "https://account-center-test.chewrobot.com/api/sdk/token";
String GET_USER_INFO_BY_TOKEN ="https://account-center-test.chewrobot.com/api/sdk/user/info";
String FLOWER_INTERFACE = "http://aws-nx2.chewrobot.com:18082/api/flower/count";
String USER_CLOOEC_LIST = "http://aliyun-hz1.chewrobot.com:18082/api/favorite";
String USER_ID_BY_TOKEN = "https://account-center-test.chewrobot.com/api/sdk/user/info";
......
......@@ -239,6 +239,44 @@ public class OkHttp3Utils {
});
}
public static void tmallBackPostAsync(String url, String requestJsonStr, Integer type) {
String header = "tianmao-jiaoyou-audio-adult-test";
if (type != null) {
switch (type) {
case 2:
case 4: header = "tianmao-jiaoyou-audio-child-test";break;
case 3:
case 5: header= "tianmao-jiaoyou-audio-adult-test";break;
default: header = "tianmao-jiaoyou-audio-test";
}
}
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr))
.header("App-Channel-Id", header)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("退出失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){
// body.string();
log.info("退出成功:{}", body.string());
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
});
}
public static void postAsync(String url, String requestJsonStr) {
Request request = new Request.Builder()
.url(url)
......
......@@ -4,6 +4,7 @@ import ai.qiwu.com.xiaoduhome.pojo.dpl.Event;
import ai.qiwu.com.xiaoduhome.pojo.pageData.HistoryData;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
......@@ -69,16 +70,25 @@ public class CollectHistoryUtils {
main.setWidth("100%");
main.setMarginBottom("20dp");
main.setFlexDirection("row");
// main.setJustifyContent("center");
// main.setAlignItems("center");
main.setComponentId("${data.botAccountId}");
main.setOnClick(Collections.singletonList(new Event("SendEvent", "${data.botAccountId}")));
// num
CollectHistoryPagePojo numContainer = new CollectHistoryPagePojo();
numContainer.setType("Container");
numContainer.setWidth("100dp");
numContainer.setJustifyContent("center");
numContainer.setAlignItems("center");
numContainer.setMarginTop("7dp");
CollectHistoryPagePojo num = new CollectHistoryPagePojo();
num.setType("Text");
num.setFontSize("40dp");
num.setMarginLeft("40dp");
num.setMarginTop("7dp");
// num.setMarginLeft("40dp");
// num.setMarginTop("7dp");
num.setText("${data.collectPageLeftNum}");
numContainer.setItems(Collections.singletonList(num));
// image
CollectHistoryPagePojo image = new CollectHistoryPagePojo();
......@@ -130,7 +140,7 @@ public class CollectHistoryUtils {
// divide.setBorderColor("rgba(255,255,255,0.3)");
// divide.setBorderWidth("0.5dp");
main.setItems(Arrays.asList(num,image, nameIntroCon, author));
main.setItems(Arrays.asList(numContainer,image, nameIntroCon, author));
return main;
}
......
......@@ -19,7 +19,7 @@ public class LunchUtils {
private static final LunchPojo LUNCH_LIST_CON = buildImgFrmTxtContainer();
private static final LunchPojo LUNCH_LIST_CATEGORY_CON = buildCategoryList();
private static final LunchPojo LUNCH_HEAD = buildLunchHead();
// private static final LunchPojo LUNCH_HEAD = buildLunchHead();
private static final LunchPojo LUNCH_BACK_IMG = buildLunchBackgroundImg();
private static final LunchPojo FOOTER = buildHomeFooter();
private static final LunchPojo CATEGORY_FOOTER = buildCategoryFooter();
......@@ -63,11 +63,11 @@ public class LunchUtils {
if (all) {
scroll = buildLunchScroll();
scroll.setItems(list);
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,LUNCH_HEAD,scroll,FOOTER));
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,scroll,FOOTER));
} else {
scroll = buildLunchPartContainer();
scroll.setItems(list);
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,LUNCH_HEAD,scroll));
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,scroll));
}
// mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,LUNCH_HEAD,LUNCH_LOGO_IMG,LUNCH_HSITORY_IMG,LUNCH_COLLECT_IMG,scroll));
......@@ -110,7 +110,7 @@ public class LunchUtils {
scroll.setMarginTop("240dp");
scroll.setItems(Arrays.asList(firstRow,secondRow));
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,LUNCH_HEAD,scroll,CATEGORY_FOOTER));
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,scroll,CATEGORY_FOOTER));
return document;
}
......@@ -263,7 +263,8 @@ public class LunchUtils {
backGroundImg.setPosition("absolute");
backGroundImg.setTop("0dp");
backGroundImg.setLeft("0dp");
backGroundImg.setSrc("https://didi-gz5.jiaoyou365.com/duai/image/backNew.jpg");
// backGroundImg.setSrc("https://didi-gz5.jiaoyou365.com/duai/image/backNew.jpg");
backGroundImg.setSrc("https://didi-gz5.jiaoyou365.com/duai/image/headImg.jpg");
backGroundImg.setHeight("100%");
backGroundImg.setScaleType("fitXY");
backGroundImg.setWidth("100%");
......@@ -299,7 +300,7 @@ public class LunchUtils {
LunchPojo footer = new LunchPojo();
footer.setType("Footer");
footer.setHints(Arrays.asList("打开第一个","打开排行榜","打开历史记录","打开分类","打开收藏","推荐作品"));
footer.setHints(Arrays.asList("打开第一个","打开排行榜","打开分类","退出","打开历史记录","打开收藏","推荐作品", "登陆"));
footerCon.setItems(Collections.singletonList(footer));
......
......@@ -448,7 +448,7 @@ public class PlayUtils {
PlayPojo footer = new PlayPojo();
footer.setType("Footer");
footer.setHints(Arrays.asList("我要送花", "收藏", "退出作品"));
footer.setHints(Arrays.asList("我要送花", "收藏", "退出作品", "重新开始"));
footerCon.setItems(Collections.singletonList(footer));
......
......@@ -226,7 +226,7 @@ public class RecommendUtil {
public static RecommandDocument getFunnyDocument(List<ProjectData> bots, String audio) {
RecommandDocument document = new RecommandDocument();
document.setDuration(90000);
document.setDuration(240000);
RecommandMainTemplate mainTemplate = new RecommandMainTemplate();
document.setMainTemplate(mainTemplate);
......
package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.common.Constants;
import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
import ai.qiwu.com.xiaoduhome.spirit.SpiritService;
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.security.RSAUtil;
import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.SecurityWrapperTaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRIVATE_KEY;
/**
* @author 苗权威
* @dateTime 19-12-6 上午10:31
......@@ -26,6 +37,8 @@ public class SpiritController {
private final SpiritRedisService spiritRedisService;
private static volatile Integer openRSA = 1;
@Autowired
public SpiritController(SpiritService spiritService, SpiritRedisService spiritRedisService) {
this.spiritService = spiritService;
......@@ -43,13 +56,21 @@ public class SpiritController {
@PostMapping(value = "/") //智能小说
public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
// log.info("天猫请求信息:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
TaskResult result;
try {
SecurityWrapperTaskQuery wrapperTaskQuery = MetaFormat.parseToWrapperQuery(taskQuery);
String decryptStr = RSAUtil.decryptByPrivateKey(wrapperTaskQuery.getSecurityQuery(), PRIVATE_KEY);
TaskQuery query = MetaFormat.parseToQuery(decryptStr);
result = spiritRedisService.getResponse(query, 5);
} catch (Exception e) {
log.warn(ExceptionUtils.getStackTrace(e));
result = bottomResponse(54808L);
}
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritRedisService.getResponse(query, 5);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
resultModel.setReturnValue(result);
// log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
return resultModel;
......@@ -58,14 +79,37 @@ public class SpiritController {
@PostMapping(value = "/smart") // 智能故事
public ResultModel<TaskResult> smart(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
TaskResult result;
// if (openRSA != 1) {
// try {
// SecurityWrapperTaskQuery wrapperTaskQuery = MetaFormat.parseToWrapperQuery(taskQuery);
// String decryptStr = RSAUtil.decryptByPrivateKey(wrapperTaskQuery.getSecurityQuery(), PRIVATE_KEY);
// TaskQuery query = MetaFormat.parseToQuery(decryptStr);
// result = spiritRedisService.getResponse(query, 4);
// } catch (Exception e) {
// log.warn(ExceptionUtils.getStackTrace(e));
// result = bottomResponse(37076L);
// }
// } else {
// TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// result = spiritRedisService.getResponse(query,4);
// }
try {
SecurityWrapperTaskQuery wrapperTaskQuery = MetaFormat.parseToWrapperQuery(taskQuery);
String decryptStr = RSAUtil.decryptByPrivateKey(wrapperTaskQuery.getSecurityQuery(), PRIVATE_KEY);
TaskQuery query = MetaFormat.parseToQuery(decryptStr);
result = spiritRedisService.getResponse(query, 4);
} catch (Exception e) {
log.warn(ExceptionUtils.getStackTrace(e));
result = bottomResponse(37076L);
}
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritRedisService.getResponse(query,4);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
resultModel.setReturnValue(result);
return resultModel;
}
......@@ -115,13 +159,34 @@ public class SpiritController {
return resultModel;
}
@PostMapping("/update/{one}")
public void updateCsvMap(@RequestBody String secId, @PathVariable String one) {
@GetMapping("/update/{one}")
public void updateCsvMap(String secId, @PathVariable String one) {
if ("qiwuAudioMqw123.".equals(secId)) {
if (one.equals(num)) {
spiritService.updateSpiritCsv();
spiritRedisService.updateSpiritCsv();
}
}
}
@GetMapping("/mark")
public void updateMark(Integer type, Integer mark) {
if (type != null) {
switch (type) {
case 1: SpiritController.openRSA = mark; break;// 1 open
// case 2: SpiritRedisService.mark = mark;break;
// case 3: SpiritRedisService.manyId = mark;break;
}
}
}
private static TaskResult bottomResponse(Long intentId) {
TaskResult result = new TaskResult();
result.setReply(Constants.ErrorMsg.SORRY_UNCATCH);
result.setResultType(ResultType.ASK_INF);
result.setExecuteCode(ExecuteCode.SUCCESS);
result.setAskedInfos(Collections.singletonList(new AskedInfoMsg("any", intentId)));
return result;
}
}
......@@ -44,7 +44,7 @@ public class XiaoAiController {
*/
@PostMapping("/")
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 交游天下
log.info("请求:"+request);
// log.info("请求:"+request);
// log.info("响应:"+response);
try {
if (!Utils.encry(5, servletRequest)) {
......@@ -52,7 +52,7 @@ public class XiaoAiController {
return null;
}
request.setType(5);
return xiaoAiService.getResponse(request);
return xiaoAiServiceRedis.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoai:"+e);
}
......@@ -60,6 +60,24 @@ public class XiaoAiController {
// return xiaoAiService.getResponse(request);
}
@PostMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request);
try {
if (!Utils.encry(2, servletRequest)) {
log.error("验证没通过:2");
return null;
}
request.setType(2);
// log.info("响应:"+response);
return xiaoAiService.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoaiAdult:"+e);
}
return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request);
}
@PostMapping("/child")
public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 智能故事
//log.info("请求:"+request);
......@@ -70,7 +88,7 @@ public class XiaoAiController {
}
request.setType(1);
// log.info("响应:"+response);
return xiaoAiService.getResponse(request);
return xiaoAiServiceRedis.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoaiChild:"+e);
}
......@@ -80,36 +98,34 @@ public class XiaoAiController {
@PostMapping("/story") //互动故事
// @RequestBody XiaoAiRequest request,
public XiaoAiResponse xiaoaiChildStory(HttpServletRequest servletRequest) {
public XiaoAiResponse xiaoaiChildStory(@RequestBody XiaoAiRequest request) {
// long start = System.currentTimeMillis();
// if (!Utils.encry(3, servletRequest)) return null;
// log.info("encry:"+(System.currentTimeMillis()-start));
try (InputStream stream = servletRequest.getInputStream()){
StringBuilder sb = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = stream.read(b)) != -1;)
{
sb.append(new String(b, 0, n));
}
String str = sb.toString();
log.info("请求:"+str);
XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
request.setType(5);
XiaoAiResponse response = xiaoAiServiceRedis.getResponse(request);
log.info("响应:"+response);
return response;
} catch (Exception e) {
}
return null;
// log.info("请求:"+request);
// try (InputStream stream = servletRequest.getInputStream()){
// StringBuilder sb = new StringBuilder();
// byte[] b = new byte[4096];
// for (int n; (n = stream.read(b)) != -1;)
// {
// sb.append(new String(b, 0, n));
// }
// String str = sb.toString();
// log.info("请求:"+str);
// XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
// request.setType(5);
// XiaoAiResponse response = xiaoAiService.getResponse(request);
// XiaoAiResponse response = xiaoAiServiceRedis.getResponse(request);
// log.info("响应:"+response);
// return response;
// return xiaoAiService.getResponse(request);
// } catch (Exception e) {
//
// }
// return null;
// log.info("请求:"+request);
request.setType(5);
// log.info("响应:"+response);
return xiaoAiServiceRedis.getResponse(request);
}
@PostMapping("/phone") //互动故事
......@@ -139,24 +155,6 @@ public class XiaoAiController {
return null;
}
@PostMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request);
try {
if (!Utils.encry(2, servletRequest)) {
log.error("验证没通过:2");
return null;
}
request.setType(2);
// log.info("响应:"+response);
return xiaoAiService.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoaiAdult:"+e);
}
return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request);
}
// @PostMapping("/literature") // 互动文艺
public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
......@@ -167,14 +165,14 @@ public class XiaoAiController {
// return xiaoAiService.getResponse(request);
}
@GetMapping("/audio/play")
public void xiaoaiPlayed(String userId) {
if (StringUtils.isNotBlank(userId)) {
log.info("小爱确认音频播放:"+userId);
xiaoAiServiceRedis.theAudioAlreadyPlay(userId);
}
else log.error("/xiaoai/audio/play userId is null");
}
// @GetMapping("/audio/play")
// public void xiaoaiPlayed(String userId) {
// if (StringUtils.isNotBlank(userId)) {
// log.info("小爱确认音频播放:"+userId);
// xiaoAiServiceRedis.theAudioAlreadyPlay(userId);
// }
// else log.error("/xiaoai/audio/play userId is null");
// }
private XiaoAiResponse buildResponse() {
XiaoAiResponse response = new XiaoAiResponse();
......
......@@ -120,9 +120,9 @@ public class XiaoDuHomeController {
//log.info("--------------分界线-------------------");
// DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
log.info("==================================");
DplBotServiceBoth service = new DplBotServiceBoth(request, 6, stringRedisTemplate);
log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
DplBotServiceBoth service = new DplBotServiceBoth(request, 5, stringRedisTemplate);
// log.info(service.getStrRequest());
log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
//service.disableVerify();
service.enableVerify();
String str = service.run();
......
......@@ -72,6 +72,7 @@ import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.BEARER;
import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.FLOWER_INTERFACE;
import static ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil.POOL;
import static ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil.USER_HISTORY;
import static ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew.curTime;
......@@ -122,7 +123,8 @@ public class DplBotServiceBoth extends BaseBot {
@Override
public Response onLaunch(LaunchRequest launchRequest) {
if (getRequest().getContext().getScreen() == null) {
// getRequest().getContext().getScreen() == null
if (isNoScreenRequest()) {
// String userId = customUserId();
stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
String welcomeWord;
......@@ -221,15 +223,16 @@ public class DplBotServiceBoth extends BaseBot {
@Override
protected Response onInent(IntentRequest intentRequest) {
if (getRequest().getContext().getScreen() == null) {
if (isNoScreenRequest()) {
final String userId = customUserId();
String redisId = SpiritRedisService.PREFIX_REDIS+userId;
// final String deviceUserId = PREFIX_USERID + getDeviceId();
try {
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisId))) {
String data = stringRedisTemplate.opsForValue().get(redisId);
if (StringUtils.isNotBlank(data)) {
log.info("超时redis获取信息:"+data);
if (StringUtils.isNotBlank(data)) {
String redisIdleId = SpiritRedisService.PREFIX_REDIS_IDLE+userId;
if (data.equals("out")) {
String idleNum = stringRedisTemplate.opsForValue().get(redisIdleId);
......@@ -238,17 +241,17 @@ public class DplBotServiceBoth extends BaseBot {
try {
Thread.sleep(2000);
} catch (Exception e){}
data = stringRedisTemplate.opsForValue().get(redisId);
if (StringUtils.isNotBlank(data) && !data.equals("out")) {
stringRedisTemplate.delete(redisIdleId);
stringRedisTemplate.delete(redisId);
Directive play = buildNoScreenPlayDirec(dealAudioUrl(data), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play);
return new Response();
}
// data = stringRedisTemplate.opsForValue().get(redisId);
// if (StringUtils.isNotBlank(data) && !data.equals("out")) {
// stringRedisTemplate.delete(redisIdleId);
// stringRedisTemplate.delete(redisId);
// Directive play = buildNoScreenPlayDirec(dealAudioUrl(data), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
// addDirective(play);
// return new Response();
// }
if (firstIdle) idleNum = "1";
else idleNum = "2";
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, TimeUnit.SECONDS);
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 {
......@@ -262,6 +265,9 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(play);
return new Response();
}
} else {
stringRedisTemplate.delete(redisId);
}
}
} catch (Exception e) {
log.error("xiaodu redis error:"+e);
......@@ -269,26 +275,61 @@ public class DplBotServiceBoth extends BaseBot {
try {
Future<Response> future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
return future.get(2700, TimeUnit.MILLISECONDS);
return future.get(2500, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
return buildErrorResponse(SORRY_UNCATCH);
} catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString());
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 10, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
return buildErrorResponse(SORRY_UNCATCH);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
return buildErrorResponse(SORRY_UNCATCH);
}
} else {
String redisId = SpiritRedisService.PREFIX_REDIS+getUserId();
String userId = getUserId();
String redisId = SpiritRedisService.PREFIX_REDIS+userId;
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisId))) {
String trace = getSessionAttribute(BACK_TRACE);
if (StringUtils.endsWith(trace, File.separator)) {
String lastData;
if ((lastData=stringRedisTemplate.opsForValue().get(redisId))!=null) {
if ("out".equals(lastData)) {
String redisIdleId = SpiritRedisService.PREFIX_REDIS_IDLE+userId;
String idleNum = stringRedisTemplate.opsForValue().get(redisIdleId);
boolean firstIdle;
if ((firstIdle = StringUtils.isBlank(idleNum)) || idleNum.equals("1")) {
try {
Thread.sleep(2000);
} catch (Exception e){}
lastData = stringRedisTemplate.opsForValue().get(redisId);
if (StringUtils.isNotBlank(lastData) && !lastData.equals("out")) {
stringRedisTemplate.delete(redisIdleId);
stringRedisTemplate.delete(redisId);
return dealScreenOutTimeResult(lastData, getUserId(), channel);
}
if (firstIdle) idleNum = "1";
else idleNum = "2";
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, 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 {
return dealScreenOutTimeResult(lastData, getUserId(), channel);
}
} else {
log.info("outtime lastData is null");
}
} else {
stringRedisTemplate.delete(redisId);
}
}
try {
Future<Response> future = DplbotServiceUtil.getPOOL().submit(() -> dealDefaultIntent(intentRequest, getUserId(),
Future<Response> future = DplbotServiceUtil.getPOOL().submit(() -> dealDefaultIntent(intentRequest, userId,
null, channel));
return future.get(2700, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
......@@ -307,7 +348,7 @@ public class DplBotServiceBoth extends BaseBot {
private Response dealScreenOutTimeResult(String data, String userId, String channelId) {
String[] arr = data.split("⧩");
log.info("outTime:"+Arrays.toString(arr));
JSONObject object = JSON.parseObject(arr[0]);
String path = arr[1];
String botAccount = object.getString("aipioneerUsername");
......@@ -340,15 +381,15 @@ public class DplBotServiceBoth extends BaseBot {
}
private Response dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
String intentName = getIntent().getName();
if ("sendFlower".equals(intentName)) {
return dealNoScreenSendFlowerIntent(userId, null);
} else if ("load".equals(intentName)) {
Card card = new LinkAccountCard();
Response response = buildErrorResponse("请在小度App上完成登录");
response.setCard(card);
return response;
}
// String intentName = getIntent().getName();
// if ("sendFlower".equals(intentName)) {
// return dealNoScreenSendFlowerIntent(userId, null);
// } else if ("load".equals(intentName)) {
// Card card = new LinkAccountCard();
// Response response = buildErrorResponse("请在小度App上完成登录");
// response.setCard(card);
// return response;
// }
try {
final Query query = intentRequest.getQuery();
......@@ -369,7 +410,7 @@ public class DplBotServiceBoth extends BaseBot {
default: channel = "jiaoyou-audio-test";break;
}
String response = RequestTerminal.requestTerminateTemp(userWord, userId, channel);
log.info("小度,小悟返回:{},",response);
// log.info("小度,小悟返回:{},",response);
if (StringUtils.isBlank(response)) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
......@@ -432,7 +473,7 @@ public class DplBotServiceBoth extends BaseBot {
log.error("推荐bot退出解析出错:"+e);
}
// String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
String path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", response);
if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
......@@ -468,8 +509,10 @@ public class DplBotServiceBoth extends BaseBot {
// WebSocketLog.sendInfo(builder.toString(), "du2");
// });
// }
log.info("Redis 写入:"+path);
stringRedisTemplate.opsForValue().set(SpiritRedisService.PREFIX_REDIS+userId, path, 10, TimeUnit.SECONDS);
if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
.setIfPresent(SpiritRedisService.PREFIX_REDIS+userId, path, 15, TimeUnit.SECONDS))) {
log.info("xiaodu 超时redis存储成功");
}
return new Response();
} catch (Exception e) {
log.warn("中控返回结果为空:"+e);
......@@ -479,7 +522,7 @@ public class DplBotServiceBoth extends BaseBot {
private String dealAudioUrl(String path) {
// return Constants.TTS_DIDI3_GET+path;
return "http://didi-gz5.jiaoyou365.com:9663/api/audio/get?path="+path;
return ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio/get?path="+path;
}
private Response dealNoScreenSendFlowerIntent(String userId, String channelId) {
......@@ -520,10 +563,14 @@ public class DplBotServiceBoth extends BaseBot {
String botId = getSessionAttribute("botAcc");
if (StringUtils.isNotBlank(botId)) {
XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
XiaoDuOrderTB response = repository.save(buildNoScreenBeforePayPojo(botId, appUserId, userId, unitPrice,
Integer.parseInt(num), orderId));
XiaoDuOrderTB tb= buildNoScreenBeforePayPojo(botId, appUserId, userId, unitPrice, Integer.parseInt(num), orderId);
if (tb == null) {
log.warn("buildNoScreenBeforePayPojo return null");
return new Response();
}
XiaoDuOrderTB response = repository.save(tb);
if (response != null && response.getId() != null) {
if (response.getId() != null) {
String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
......@@ -557,6 +604,14 @@ public class DplBotServiceBoth extends BaseBot {
*/
private Response dealOpenNum(String idsToken, int collectNum) {
String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
int curIndex = 0;
String nextPageIndex = getSessionAttribute(NEXT_PAGE_INDEX);
if (StringUtils.isNotBlank(nextPageIndex)) {
curIndex = Integer.parseInt(nextPageIndex)-1;
curIndex = curIndex < 0 ? 0 : curIndex;
}
collectNum = collectNum-curIndex*CO_HI_PAGE_SIZE;
if (collectNum <= 0 || collectNum > tokenList.length) return buildErrorResponse("请说出您要打开的作品在当前页面所显示的数字");
String botID = tokenList[collectNum-1];
ProjectData detail = ScheduleServiceNew.getProjectByBotAccount(botID);
String productName = correctName(detail.getName());
......@@ -575,7 +630,7 @@ public class DplBotServiceBoth extends BaseBot {
String path = null;
try {
path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", data);
} catch (Exception e) {
log.warn("没有获取到TTS返回地址");
}
......@@ -606,8 +661,45 @@ public class DplBotServiceBoth extends BaseBot {
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();
......@@ -697,7 +789,7 @@ public class DplBotServiceBoth extends BaseBot {
String path = null;
try {
path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", data);
} catch (Exception e) {
log.warn("没有获取到TTS返回地址");
}
......@@ -792,7 +884,7 @@ public class DplBotServiceBoth extends BaseBot {
case USER_INITIATED: log.info(EndMsg.USER_SAY_CANCEL); break;
case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
}
if (getRequest().getContext().getScreen() == null) {
if (isNoScreenRequest()) {
String userId = customUserId();
String byeWord = EndMsg.END_BYE_Adult;
switch (type) {
......@@ -838,7 +930,7 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(render);
setSessionAttribute(PRE_COLLE,document.getIdToken());
setSessionAttribute("recommand", null);
setSessionAttribute("comCnt", null);
setSessionAttribute(NEXT_PAGE_INDEX, null);
setSessionAttribute(BACK_TRACE, "02");
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开历史记录");
return new Response(outputSpeech);
......@@ -870,7 +962,7 @@ public class DplBotServiceBoth extends BaseBot {
if (document != null) {
RenderDocument render = new RenderDocument(document);
addDirective(render);
setSessionAttribute("comCnt", null);
setSessionAttribute(NEXT_PAGE_INDEX, null);
setSessionAttribute(PRE_COLLE,document.getIdToken());
setSessionAttribute(BACK_TRACE, "01");
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开收藏夹");
......@@ -997,11 +1089,12 @@ public class DplBotServiceBoth extends BaseBot {
log.info("登录成功返回信息:{}",linkAccountSucceededEvent);
String accessToken = getAccessToken();
String jytUserId;
if (getRequest().getContext().getScreen() != null) {
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 {
......@@ -1164,7 +1257,7 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(index+1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
setSessionAttribute(PRE_COLLE, document.getRecommendIdList());
return new Response();
}
......@@ -1182,25 +1275,35 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(index+1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
return new Response();
}
private Response dealCollectHistoryJump(int index, boolean collect, String userId, String channelId) {
index = index == 0 ? index : index-1;
if (index < 0) return buildErrorResponse("这个数字超出了范围");
String nextPageIndex = getSessionAttribute(NEXT_PAGE_INDEX);
if (StringUtils.isBlank(nextPageIndex) && index <= 1) return buildErrorResponse(
"您已经在第一页了,请看右上角当前页和总页数的提示");
else if (String.valueOf(index).equals(nextPageIndex)) return buildErrorResponse("您已经在第"+index+"页了,请看右上角当前页和总页数的提示");
index = index <= 1 ? 0 : index-1;
int start = index*CO_HI_PAGE_SIZE;
CollectHistoryDocument document;
if (collect) document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
getSessionAttribute("userId"), start, channelId);
else document = DplbotServiceUtil.getHistory(userId, getAccessToken(), getSessionAttribute("userId"),start,channelId);
if (document != null) {
if ("1".equals(document.getIdToken())) {
log.info("dealCollectHistoryJump:-->"+1);
return buildErrorResponse("您要打开的页数超出了范围");
}
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(index+1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
setSessionAttribute(PRE_COLLE, document.getIdToken());
return new Response();
} else {
log.info("dealCollectHistoryJump:-->document is null");
return buildErrorResponse("超出了范围无法跳到那一页");
}
}
......@@ -1237,7 +1340,8 @@ public class DplBotServiceBoth extends BaseBot {
String botId;
String trace = getSessionAttribute(BACK_TRACE);
if (trace != null && trace.length() > 2) {
if (StringUtils.endsWith(trace, File.separator)) {
boolean inPlay;
if ((inPlay=StringUtils.endsWith(trace, File.separator))) {
botId = trace.substring(2, trace.length()-1);
}else {
botId = trace.substring(2);
......@@ -1255,7 +1359,7 @@ public class DplBotServiceBoth extends BaseBot {
if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
.append("的").append(num).append("朵鲜花").toString();
Charge charge = new Charge(amount, orderId, "鲜花", desc);
charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
charge.setToken(new StringBuilder(botId).append(File.separator).append(num).append(File.separator).append(inPlay?1:0).toString());
addDirective(charge);
return buildErrorResponse("请扫描二维码完成支付");
} else {
......@@ -1354,7 +1458,7 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(render);
String token = document.getRecommendIdList();
setSessionAttribute(PRE_COLLE, token);
setSessionAttribute("comCnt", null);
setSessionAttribute(NEXT_PAGE_INDEX, null);
setSessionAttribute(BACK_TRACE, "04");
return buildErrorResponse("正在为您打开排行榜");
}
......@@ -1369,9 +1473,9 @@ public class DplBotServiceBoth extends BaseBot {
if (token != null) {
setSessionAttribute("recommand", token);
setSessionAttribute(PRE_COLLE, null);
setSessionAttribute("comCnt", null);
setSessionAttribute(NEXT_PAGE_INDEX, null);
detail.getAttributes().put("comCnt", null);
detail.getAttributes().put(NEXT_PAGE_INDEX, null);
detail.getAttributes().put("recommand", token);
detail.getAttributes().put(PRE_COLLE, null);
}
......@@ -1398,7 +1502,7 @@ public class DplBotServiceBoth extends BaseBot {
//dplBotService.addDirective(new PushStack());
setSessionAttribute(PRE_COLLE,document.getIdToken());
// setSessionAttribute("recommand", null);
// setSessionAttribute("comCnt", null);
// setSessionAttribute(NEXT_PAGE_INDEX, null);
setSessionAttribute(BACK_TRACE, "02");
return buildErrorResponse("正在为您打开历史记录");
}
......@@ -1411,7 +1515,7 @@ public class DplBotServiceBoth extends BaseBot {
char sign = signPage.charAt(1);
switch (sign) {
case '1': {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null) {
recommendNextCount = "1";
}
......@@ -1428,13 +1532,13 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(count+1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
setSessionAttribute(PRE_COLLE, document.getIdToken());
}
return new Response();
}
case '2': {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null) {
recommendNextCount = "1";
}
......@@ -1446,13 +1550,13 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(count+1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
setSessionAttribute(PRE_COLLE, document.getIdToken());
}
return new Response();
}
case '3': {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
RecommandDocument document = RecommendUtil.getRecommendDocument(count,channelId);
......@@ -1463,11 +1567,11 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(render);
String token = document.getRecommendIdList();
setSessionAttribute(PRE_COLLE, token);
setSessionAttribute("comCnt",String.valueOf(count+1));
setSessionAttribute(NEXT_PAGE_INDEX,String.valueOf(count+1));
return new Response();
}
case '4': {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
RecommandDocument document = RecommendUtil.getRankOtherPageDocument(count, channelId);
......@@ -1478,13 +1582,13 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(render);
String token = document.getRecommendIdList();
setSessionAttribute(PRE_COLLE, token);
setSessionAttribute("comCnt",String.valueOf(count+1));
setSessionAttribute(NEXT_PAGE_INDEX,String.valueOf(count+1));
return new Response();
}
case '5':{
String category = getSessionAttribute("category");
if (category == null) category = "古风";
String categoryNextCount = getSessionAttribute("comCnt");
String categoryNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (categoryNextCount != null) count = Integer.parseInt(categoryNextCount);
RecommandDocument document = RecommendUtil.getCategory(count,category);
......@@ -1494,7 +1598,7 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String countStr = String.valueOf(count+1);
setSessionAttribute("comCnt",countStr);
setSessionAttribute(NEXT_PAGE_INDEX,countStr);
return new Response();
}
default:{
......@@ -1511,7 +1615,7 @@ public class DplBotServiceBoth extends BaseBot {
char sign = signPage.charAt(1);
switch (sign) {
case '1':{
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null || "1".equals(recommendNextCount)) {
return buildErrorResponse("客观,前面没啦,没法往前翻了");
}
......@@ -1528,13 +1632,13 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(count-1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
setSessionAttribute(PRE_COLLE, document.getIdToken());
}
break;
}
case '2':{
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null || "1".equals(recommendNextCount)) {
return buildErrorResponse("客观,前面没啦,没法往前翻了");
}
......@@ -1546,13 +1650,13 @@ public class DplBotServiceBoth extends BaseBot {
RenderDocument render = new RenderDocument(document);
addDirective(render);
String cmt = String.valueOf(count-1);
setSessionAttribute("comCnt",cmt);
setSessionAttribute(NEXT_PAGE_INDEX,cmt);
setSessionAttribute(PRE_COLLE, document.getIdToken());
}
break;
}
case '3': {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null || "1".equals(recommendNextCount)) {
return buildErrorResponse("客观,前面没啦,没法往前翻了");
}
......@@ -1563,12 +1667,12 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(render);
String token = document.getRecommendIdList();
setSessionAttribute(PRE_COLLE, token);
setSessionAttribute("comCnt",String.valueOf(count-1));
setSessionAttribute(NEXT_PAGE_INDEX,String.valueOf(count-1));
}
break;
}
case '4': {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null || "1".equals(recommendNextCount)) {
return buildErrorResponse("客观,前面没啦,没法往前翻了");
}
......@@ -1581,14 +1685,14 @@ public class DplBotServiceBoth extends BaseBot {
addDirective(render);
String token = document.getRecommendIdList();
setSessionAttribute(PRE_COLLE, token);
setSessionAttribute("comCnt",String.valueOf(count-1));
setSessionAttribute(NEXT_PAGE_INDEX,String.valueOf(count-1));
}
break;
}
case '5':{
String category = getSessionAttribute("category");
if (category == null) category = "古风";
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
if (recommendNextCount == null || "1".equals(recommendNextCount)) {
return buildErrorResponse("客观,前面没啦,没法往前翻了");
}
......@@ -1596,7 +1700,7 @@ public class DplBotServiceBoth extends BaseBot {
RecommandDocument document = RecommendUtil.getCategory(count-2,category);
RenderDocument render = new RenderDocument(document);
addDirective(render);
setSessionAttribute("comCnt",String.valueOf(count-1));
setSessionAttribute(NEXT_PAGE_INDEX,String.valueOf(count-1));
break;
}
default:{
......@@ -1621,8 +1725,8 @@ public class DplBotServiceBoth extends BaseBot {
case '1':
case '2': response = dealOpenNum(getSessionAttribute(PRE_COLLE), num); break;
case '3':
case '4':
case '6': response = dealOpenNumInRecommend(getSessionAttribute(PRE_COLLE), num, channelId); break;
case '4': response = dealOpenNumInRecommend(getSessionAttribute(PRE_COLLE), num, channelId, true); break;
case '6': response = dealOpenNumInRecommend(getSessionAttribute(PRE_COLLE), num, channelId, false); break;
case '5': response = dealOpenNumInCategoryBots(channelId, num);break;
case '7': response = dealOpenNumCategory(num);break;
default:{
......@@ -1730,7 +1834,7 @@ public class DplBotServiceBoth extends BaseBot {
appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken(), channelId);
}
}
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),appUserId,
......@@ -1747,7 +1851,7 @@ public class DplBotServiceBoth extends BaseBot {
}
case '2': {
//history
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(),getSessionAttribute("userId"),
......@@ -1764,7 +1868,7 @@ public class DplBotServiceBoth extends BaseBot {
}
case '3': {
//recommend
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(count-1, channelId);
......@@ -1785,7 +1889,7 @@ public class DplBotServiceBoth extends BaseBot {
}
case '4': {
//rank
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
RecommandDocument recommandDocument;
......@@ -1811,7 +1915,7 @@ public class DplBotServiceBoth extends BaseBot {
if (category == null) {
backToHome();
} else {
String count = getSessionAttribute("comCnt");
String count = getSessionAttribute(NEXT_PAGE_INDEX);
int pageIndex = 0;
if (count != null) pageIndex = Integer.parseInt(count)-1;
RecommandDocument document = RecommendUtil.getCategory(pageIndex, category);
......@@ -1864,50 +1968,51 @@ public class DplBotServiceBoth extends BaseBot {
if (StringUtils.isNotBlank(command)) {
if ((i=command.indexOf("out")) != -1) {
log.info("小度,推荐bot退出:{},{}",word,userId);
String content = command.substring(i+3).trim();
String byeWord = null;
String skillName = null;
switch (type) {
case 1: {
byeWord = EndMsg.END_BYE_STORY;
skillName = SKILL_SMART;
break;
}
case 2: {
byeWord = EndMsg.END_BYE_NOVEL;
skillName = SKILL_NOVEL;
break;
}
case 5: {
byeWord = EndMsg.END_BYE_JIAOYOU;
skillName = SKILL;
break;
}
}
if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
if (skillName == null) skillName = SKILL_DEFAULT;
if (StringUtils.isBlank(content)) {
JSONArray dialogs = object.getJSONArray("dialogs");
if (dialogs != null && dialogs.size() != 0) {
String str = ((JSONObject)dialogs.get(0)).getString("text");
if (StringUtils.isNotBlank(str)) {
str = str.replaceAll("\\{/.*?/}", "")+skillName;
RequestTerminal.backRequest(userId, type);
return buildLogOutResponse(str);
}
}
RequestTerminal.backRequest(userId, type);
return buildLogOutResponse(byeWord);
} else {
content = content.replaceAll("\\{/.*?/}", "")+skillName;
RequestTerminal.backRequest(userId, type);
return buildLogOutResponse(content);
}
return buildErrorResponse("本技能暂不支持该功能,若您想要退技能,请说小度小度,退出");
// String content = command.substring(i+3).trim();
// String byeWord = null;
// String skillName = null;
// switch (type) {
// case 1: {
// byeWord = EndMsg.END_BYE_STORY;
// skillName = SKILL_SMART;
// break;
// }
// case 2: {
// byeWord = EndMsg.END_BYE_NOVEL;
// skillName = SKILL_NOVEL;
// break;
// }
// case 5: {
// byeWord = EndMsg.END_BYE_JIAOYOU;
// skillName = SKILL;
// break;
// }
// }
// if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
// if (skillName == null) skillName = SKILL_DEFAULT;
// if (StringUtils.isBlank(content)) {
// JSONArray dialogs = object.getJSONArray("dialogs");
// if (dialogs != null && dialogs.size() != 0) {
// String str = ((JSONObject)dialogs.get(0)).getString("text");
// if (StringUtils.isNotBlank(str)) {
// str = str.replaceAll("\\{/.*?/}", "")+skillName;
// RequestTerminal.backRequest(userId, type);
// return buildLogOutResponse(str);
// }
// }
// RequestTerminal.backRequest(userId, type);
// return buildLogOutResponse(byeWord);
// } else {
// content = content.replaceAll("\\{/.*?/}", "")+skillName;
// RequestTerminal.backRequest(userId, type);
// return buildLogOutResponse(content);
// }
}
String locate = getSessionAttribute("locate");
if (locate != null) setSessionAttribute("locate", null);
switch (command) {
case "recommend": return dealRecommend(data, object);
case "recommend": return dealRecommend(data, object, true);
case "history" : return dealHistoryIntent(channelId);
case "collect" : return dealOpenCollectIntent(channelId);
case "next" : return dealNextPageIntent(userId,channelId);
......@@ -1935,7 +2040,7 @@ public class DplBotServiceBoth extends BaseBot {
}
}
} catch (Exception e) {
log.error("推荐bot退出解析出错:"+e);
log.error("解析出错:"+e);
return new Response();
}
boolean endMark = false;
......@@ -1978,9 +2083,12 @@ public class DplBotServiceBoth extends BaseBot {
String botAccount = object.getString("aipioneerUsername");
if (StringUtils.isBlank(botAccount)) return new Response();
if (botAccount.equals(ScheduleServiceNew.getTheChannelBotAccount(channelId))){
return dealRecommend(data, object, false);
}
String path = null;
try {
path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", data);
} catch (Exception e) {
log.warn("没有获取到TTS返回地址");
}
......@@ -1989,9 +2097,6 @@ public class DplBotServiceBoth extends BaseBot {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
if (botAccount.equals(ScheduleServiceNew.getTheChannelBotAccount(channelId))){
return dealRecommend(data, object);
}
String beforeBotAccount = getSessionAttribute("botAcc");
if (!botAccount.equals(beforeBotAccount)) {
DplbotServiceUtil.updateTheUserBehaviorDataMark(userId, botAccount, getAccessToken(), getSessionAttribute("userId"), channelId);
......@@ -2161,15 +2266,15 @@ public class DplBotServiceBoth extends BaseBot {
return new Response();
}
private Response dealRecommend(String data, JSONObject object) {
private Response dealRecommend(String data, JSONObject object, boolean hasOrder) {
try {
String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
String path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", data);
if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
String text = ((JSONObject) object.getJSONArray("dialogs").get(0)).getString("text");
if (!text.contains("推荐如下")) {
if (!hasOrder && !text.contains("推荐如下")) {
String trace = getSessionAttribute(BACK_TRACE);
char type='0';
int ln;
......@@ -2284,7 +2389,7 @@ public class DplBotServiceBoth extends BaseBot {
private Response dealCategoryBotBottom(String src) {
String category = getSessionAttribute("category");
if (category == null) category = "古风";
String categoryNextCount = getSessionAttribute("comCnt");
String categoryNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 0;
if (categoryNextCount != null) {
count = Integer.parseInt(categoryNextCount);
......@@ -2301,7 +2406,7 @@ public class DplBotServiceBoth extends BaseBot {
}
private Response dealRankBottom(String channelId, String src) {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count = 1;
if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
RecommandDocument document = RecommendUtil.getRankOtherPageDocument(count, channelId);
......@@ -2315,7 +2420,7 @@ public class DplBotServiceBoth extends BaseBot {
}
private Response dealHistoryOrCollectBottom(String userId, String channelId, String src, boolean collect) {
String recommendNextCount = getSessionAttribute("comCnt");
String recommendNextCount = getSessionAttribute(NEXT_PAGE_INDEX);
int count;
if (recommendNextCount == null) {
count = 0;
......@@ -2345,12 +2450,23 @@ public class DplBotServiceBoth extends BaseBot {
return new Response();
}
private Response dealOpenNumInRecommend(String idsToken, int collectNum, String channelId) {
private Response dealOpenNumInRecommend(String idsToken, int collectNum, String channelId, boolean rank) {
if (idsToken == null) {
return buildErrorResponse("请重新进入当前页面");
}
String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
if (collectNum > tokenList.length || collectNum <= 0) return buildErrorResponse("这个数字超出了范围");
if (rank) {
int index;
String currentNextPage = getSessionAttribute(NEXT_PAGE_INDEX);
if (StringUtils.isNotBlank(currentNextPage)) {
index = Integer.parseInt(currentNextPage)-1;
index = index < 0 ? 0 : index;
} else {
index = 0;
}
collectNum = collectNum-index*RE_RA_CA_PAGE_SIZE;
}
if (collectNum > tokenList.length || collectNum <= 0) return buildErrorResponse("这个数字超出了范围,请说出您要打开的作品在当前页面所显示的数字");
ProjectData detail = ScheduleServiceNew.getProjectByBotAccount(tokenList[collectNum-1]);
String accessToken = getAccessToken();
if (DplbotServiceUtil.doesUserPlayed(detail.getBotAccount(), getUserId(), accessToken, accessToken != null)) {
......@@ -2373,7 +2489,7 @@ public class DplBotServiceBoth extends BaseBot {
}
private Response dealOpenNumInCategoryBots(String channelId, int num) {
String count = getSessionAttribute("comCnt");
String count = getSessionAttribute(NEXT_PAGE_INDEX);
String category = getSessionAttribute("category");
if (StringUtils.isBlank(category)) return buildErrorResponse("请直接点击进入");
int pageIndex = 0;
......@@ -2390,7 +2506,7 @@ public class DplBotServiceBoth extends BaseBot {
response = directInProduct(bot.getName(), bot.getBotAccount());
} else response = enterProductInfo(bot.getName(), channelId);
setSessionAttribute("category", category);
setSessionAttribute("comCnt", count);
setSessionAttribute(NEXT_PAGE_INDEX, count);
return response;
}
......@@ -2427,9 +2543,11 @@ public class DplBotServiceBoth extends BaseBot {
}
}
private Response directInProduct(String name,String botId) {
private Response directInProduct(final String name,final String botId) {
addDirective(new SendPart("direct"));
POOL.submit(() -> {
String productName = correctName(name);
String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
String enterProductWord = Constants.PRE_PRODUCT_PLAY + productName;
log.info("进入作品语句:{}", enterProductWord);
String data = null;
try {
......@@ -2438,29 +2556,12 @@ public class DplBotServiceBoth extends BaseBot {
log.error("请求终端接口出错:", e.toString());
}
if (data == null) {
return buildErrorResponse(SORRY_UNCATCH);
}
String path = null;
try {
path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
} catch (Exception e) {
log.warn("没有获取到TTS返回地址");
}
if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
return;
}
PlayDocument document = PlayUtils.getPlayDocument(productName,
DplbotServiceUtil.getTheActorsWithWords(JSON.parseObject(data).getJSONArray("dialogs")), 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);
return new Response();
stringRedisTemplate.opsForValue().set(SpiritRedisService.PREFIX_REDIS_DIRECT+getUserId(),
data, 15, TimeUnit.SECONDS);
});
return buildErrorResponse("晓悟正在为您打开"+name+",请您稍等");
}
private Response enterProductInfo(String productName, String channelId) {
......@@ -2589,32 +2690,38 @@ public class DplBotServiceBoth extends BaseBot {
xiaoDuOrderTB.setStatus(false);
xiaoDuOrderTB.setChOrderId(orderId);
xiaoDuOrderTB.setTimeStamp(curTime);
xiaoDuOrderTB.setChannelId(channel);
}
@Override
protected Response onChargeEvent(ChargeEvent chargeEvent) {
String token = chargeEvent.getToken();
int sepIndex = token.indexOf(File.separator);
final String botAccount = token.substring(0, sepIndex);
String[] tokens = token.split(File.separator);
log.info("onChargeEvent token:"+token);
final String botAccount = tokens[0];
String str = "恭喜您支付成功,开始体验吧";
if (getRequest().getContext().getScreen() != null) {
if (!isNoScreenRequest()) {
String userId = getUserId();
String jytUserId = getSessionAttribute("userId");
boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(),
Boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(),
jytUserId, ScheduleServiceNew.getWorkNameByBotAccount(botAccount), channel);
if (response) {
log.info("onChargeEvent response:"+response);
if (Boolean.TRUE.equals(response)) {
Map<String, Long> flowerRecords = USER_HISTORY.get(userId).getUserBotId2Flowers();
Long before = flowerRecords.get(botAccount);
if (before == null) before = 0L;
flowerRecords.put(botAccount, ++before);
DplbotServiceUtil.noticeOtherServer(2, botAccount, before, false, userId, jytUserId, channel, true);
ExecuteCommands executeCommands = new ExecuteCommands();
SetStateCommand stateCommand = new SetStateCommand();
stateCommand.setComponentId("pft");
stateCommand.setState("text");
stateCommand.setValue(USER_SEND_FLOWER+before);
executeCommands.addCommand(stateCommand);
addDirective(executeCommands);
try {
if ("0".equals(tokens[2])) {
log.info("onChargeEvent in project info:{}, token:{}",before,token);
enterProductInfo(ScheduleServiceNew.getWorkNameByBotAccount(botAccount), channel);
// addDirective(new SendPart("payed"));
str = "恭喜您支付成功";
}
} catch (Exception e) {
log.warn(ExceptionUtils.getStackTrace(e));
}
} else {
str = "很抱歉,您没有支付成功";
}
......@@ -2643,44 +2750,7 @@ public class DplBotServiceBoth extends BaseBot {
// log.info("音频播放完毕,开麦");
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
// log.error("FinishedEvent");
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("http://didi-gz5.jiaoyou365.com: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 {
this.setExpectSpeech(true);
}
return new Response();
}
......@@ -2694,10 +2764,10 @@ public class DplBotServiceBoth extends BaseBot {
@Override
protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
if (getRequest().getContext().getScreen() == null) {
Boolean result = stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
log.info("音频播放事件删除:"+result);
}
// if (isNoScreenRequest()) {
// Boolean result = stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
// log.info("音频播放事件删除:"+result);
// }
waitAnswer();
return new Response();
}
......@@ -2730,6 +2800,53 @@ public class DplBotServiceBoth extends BaseBot {
}
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")), 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));
......@@ -2757,4 +2874,14 @@ public class DplBotServiceBoth extends BaseBot {
// 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);
}
}
......@@ -132,6 +132,7 @@ public class DplbotServiceUtil {
} catch (Exception e) {
log.error("获取郊游天下用户id出错:{}", ExceptionUtils.getStackTrace(e));
}
return null;
}
......@@ -204,7 +205,7 @@ public class DplbotServiceUtil {
Map<String, Long> map = new HashMap<>();
for (XiaoDuHistoryTB xiaoDuHistoryTB: historyTBS) {
if (StringUtils.isBlank(jytId)) jytId = xiaoDuHistoryTB.getJytUserId();
String botAccount = ScheduleServiceNew.getWorkNameByBotAccount(xiaoDuHistoryTB.getWorkName());
String botAccount = ScheduleServiceNew.getBotAccountByWorkname(xiaoDuHistoryTB.getWorkName());
if (StringUtils.isNotBlank(botAccount)) map.put(botAccount, xiaoDuHistoryTB.getUpdateTime().getTime());
else log.warn("onLunchFillUserBehaviorDataInMaster: 历史数据库存储信息与缓存不一致");
}
......@@ -225,7 +226,7 @@ public class DplbotServiceUtil {
Map<String, Long> map = new HashMap<>();
for (XiaoDuOrderTB xiaoDuOrderTB: orderTBS) {
if (StringUtils.isBlank(jytId)) jytId = xiaoDuOrderTB.getAppUserId();
String botAccount = ScheduleServiceNew.getWorkNameByBotAccount(xiaoDuOrderTB.getWorkName());
String botAccount = ScheduleServiceNew.getBotAccountByWorkname(xiaoDuOrderTB.getWorkName());
if (StringUtils.isNotBlank(botAccount)) map.put(botAccount, xiaoDuOrderTB.getNumber());
else log.warn("onLunchFillUserBehaviorDataInMaster: 送花数据库存储信息与缓存不一致");
}
......@@ -413,7 +414,8 @@ public class DplbotServiceUtil {
}
String botId;
if (trace != null && trace.length() > 2) {
if (StringUtils.endsWith(trace, File.separator)) {
boolean inPlay;
if ((inPlay=StringUtils.endsWith(trace, File.separator))) {
botId = trace.substring(2, trace.length()-1);
}else {
botId = trace.substring(2);
......@@ -429,7 +431,7 @@ public class DplbotServiceUtil {
if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
.append("的").append(1).append("朵鲜花").toString();
Charge charge = new Charge(amount, orderId, "鲜花", desc);
charge.setToken(new StringBuilder(botId).append(File.separator).append(1).toString());
charge.setToken(new StringBuilder(botId).append(File.separator).append(1).append(File.separator).append(inPlay ? 1 : 0).toString());
return charge;
} else {
log.error("订单没有插入到xioadu_order_tb");
......@@ -519,19 +521,18 @@ public class DplbotServiceUtil {
}
}
static boolean dealChargeCallback(ChargeEvent chargeEvent, final String userId, final String accessToken,
static Boolean dealChargeCallback(ChargeEvent chargeEvent, final String userId, final String accessToken,
final String jytUserId, String workName, String channelId) {
Payload payload = chargeEvent.getPayload();
final String chOrderId = chargeEvent.getSellerOrderId();
String token = chargeEvent.getToken();
int sepIndex = token.indexOf(File.separator);
final String botAccount = token.substring(0, sepIndex);
String[] tokens = chargeEvent.getToken().split(File.separator);
final String botAccount = tokens[0];
if (payload.getPurchaseResult().equals("SUCCESS")) {
// createTimestamp字段与baiduOrderReferenceId字段与之后百度方进行结算使用,
// 现在createTimestamp由于百度方的bug需等到九月份才能获取到
final String baiduOrderReferenceId = payload.getBaiduOrderReferenceId();
final String createTimestamp = payload.getAuthorizationDetails().getCreationTimestamp();
final String num = token.substring(sepIndex+1);
final String num = tokens[1];
POOL.submit(() -> {
XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
......@@ -590,11 +591,11 @@ public class DplbotServiceUtil {
if (StringUtils.isAnyBlank(botAccount, userId)) return;
UserBehaviorData data = USER_HISTORY.get(userId);
if (data != null) {
log.info("updateTheUserBehaviorDataMark: data is null");
data.setMark(1);
data.getUserBotId2History().put(botAccount, curTime);
noticeOtherServer(1, botAccount, ScheduleServiceNew.curTime, false, userId, jytUserId, channel, accessToken!= null);
} else {
log.info("updateTheUserBehaviorDataMark: data is null");
data = onLunchFillUserBehaviorDataInMaster(userId, channel, jytUserId, accessToken != null);
if (data != null) {
data.getUserBotId2History().put(botAccount, curTime);
......@@ -616,6 +617,7 @@ public class DplbotServiceUtil {
}
static CollectHistoryDocument getCollectPage(String userId, String accessToken, String jytId, int start, String channelId) {
log.info("getCollectPage:start->"+start);
UserBehaviorData behaviorData = USER_HISTORY.get(userId);
int pageNum;
if (behaviorData == null) {
......@@ -635,13 +637,14 @@ public class DplbotServiceUtil {
return null;
}
pageNum = bound/CO_HI_PAGE_SIZE + (bound%CO_HI_PAGE_SIZE == 0 ? 0 : 1);
log.info("getCollectPage:pageNum->"+pageNum);
// log.info("collect/history: pagesize:{},bound{}",pageNum,bound);
TreeMap<Long, String> order = new TreeMap<>((o1, o2) -> (o1 < o2) ? 1 : ((o1.equals(o2)) ? 0 : -1));
for (Map.Entry<String, Long> entry: userBotId2Collected.entrySet()) {
order.put(entry.getValue(), entry.getKey());
}
List<String> favoriteProducts = new ArrayList<>();
int i = 0, e = start+CO_HI_PAGE_SIZE;
int i = 0, e = start+CO_HI_PAGE_SIZE >= bound ? bound : start+CO_HI_PAGE_SIZE;
for (Map.Entry<Long, String> entry: order.entrySet()) {
if (i == e) break;
if (i++ >= start) {
......@@ -679,6 +682,7 @@ public class DplbotServiceUtil {
}
static CollectHistoryDocument getHistory(String userId, String accessToken,String jytUserId, int start, String channelId) {
log.info("getHistory:start->"+start);
List<XiaoDuHistoryBotIdTime> historyProducts = new ArrayList<>();
UserBehaviorData behaviorData = USER_HISTORY.get(userId);
int pageNum = 0;
......@@ -699,6 +703,7 @@ public class DplbotServiceUtil {
return null;
}
pageNum = bound/CO_HI_PAGE_SIZE + (bound%CO_HI_PAGE_SIZE == 0 ? 0 : 1);
log.info("getHistory:pageNum->"+pageNum);
TreeMap<Long, String> order = new TreeMap<>((o1, o2) -> (o1 < o2) ? 1 : ((o1.equals(o2)) ? 0 : -1));
for (Map.Entry<String, Long> entry: behaviorData.getUserBotId2History().entrySet()) {
order.put(entry.getValue(), entry.getKey());
......@@ -815,7 +820,14 @@ public class DplbotServiceUtil {
switch (type) {
case 1 : behaviorData.getUserBotId2History().put(data.getBotAccount(), data.getTimeOrCount()); break;
case 2 : behaviorData.getUserBotId2Flowers().put(data.getBotAccount(), data.getTimeOrCount()); break;
case 3 : behaviorData.getUserBotId2Collected().put(data.getBotAccount(), data.getTimeOrCount()); break;
case 3 : {
if (Boolean.TRUE.equals(data.getCollect())) {
behaviorData.getUserBotId2Collected().put(data.getBotAccount(), data.getTimeOrCount());
} else {
behaviorData.getUserBotId2Collected().remove(data.getBotAccount());
}
break;
}
}
}
......
......@@ -207,7 +207,20 @@ public class LoadBySMS {
// return ACCESSTOKEN_PHONENUM;
// }
public static void main(String[] args) {
System.out.println(getTokenByRefreshToken("4e929ca8-6db1-4224-be1e-e8f5a4f6bdb5"));
public static void main(String[] args) throws IOException {
// HashMap<String, String> headers = new HashMap<>();
// headers.put("App-Channel-Id", "JIAOYOUTIANXIA");
// headers.put("Content-Type", "application/json;charset=utf-8");
// headers.put("Authorization", Utils.tokenAuthorization("13922841032", "7210"));
// String tokenStr = OkHttp3Utils.doGet(XIAOWU_API.SDK_TOKEN, new HashMap<>(), headers);
//// log.info("获取Token返回");
// System.out.println(tokenStr);
HashMap<String, String> headers = new HashMap<>();
headers.put("App-Channel-Id", "JIAOYOUTIANXIA");
headers.put("Content-Type", "application/json;charset=utf-8");
headers.put("Authorization", Utils.captchaAuthorization("13410129349"));
String smsStr = OkHttp3Utils.doGet(XIAOWU_API.CAPTCHA_SMS, new HashMap<>(), headers);
System.out.println(smsStr);
}
}
......@@ -53,7 +53,7 @@ class RequestTerminal {
// default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
// }
// return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
return OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, headers);
return OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, headers);
}
static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException {
......@@ -105,7 +105,7 @@ class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg("退出");
String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttp3Utils.backPostAsync("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, type);
OkHttp3Utils.backPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
// OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
}
......
......@@ -50,6 +50,8 @@ public class ScheduleServiceNew implements InitializingBean {
private static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>();
public static volatile String BASE_HOST_URL = Config.getProperty("baseHostUrl", "http://didi-gz2.jiaoyou365.com:");;
@Override
public void afterPropertiesSet() throws Exception {
getAllProjects();
......@@ -135,7 +137,7 @@ public class ScheduleServiceNew implements InitializingBean {
@Scheduled(cron = "0 */2 * * * ?")
public void updateTheCurTime() {
log.info("updateTheCurTime start");
// log.info("updateTheCurTime start");
curTime = System.currentTimeMillis();
}
......
package ai.qiwu.com.xiaoduhome.spirit;
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.service.DplbotServiceUtil;
import ai.qiwu.com.xiaoduhome.service.ScheduleService;
import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestTerminal;
import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
import com.alibaba.da.coin.ide.spi.meta.Action;
import com.alibaba.da.coin.ide.spi.meta.AskedInfoMsg;
......@@ -11,6 +15,8 @@ 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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.dueros.data.response.directive.Directive;
import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
import com.baidu.dueros.model.Response;
......@@ -34,6 +40,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.SKILL_DEFAULT;
import static ai.qiwu.com.xiaoduhome.spirit.InitialData.*;
import static ai.qiwu.com.xiaoduhome.spirit.InitialData.botAccount2ItsCache;
......@@ -50,6 +58,9 @@ public class SpiritRedisService {
@Value("${csvChildDic}")
private String csvChildDic;
// public static volatile Integer mark = 1;
// public static volatile Integer manyId = 1;
private static final String AB_REGEX = "\uD83C\uDD70(.*?)\uD83C\uDD71";
private final StringRedisTemplate stringRedisTemplate;
......@@ -58,6 +69,10 @@ public class SpiritRedisService {
public static final String PREFIX_REDIS_IDLE = "audio_idle_";
public static final String PREFIX_REDIS_DIRECT = "audio_direct_";
private static final String PREFIX_TMALL = "TMALL_";
// private static final HashMap<String, String> ADULT_HEADER;
// private static final HashMap<String, String> CHILD_HEADER;
//
......@@ -90,8 +105,18 @@ public class SpiritRedisService {
private TaskResult getNeededParam(TaskQuery request, int type) {
String userId = getUserId(request);
String redisId = PREFIX_REDIS+userId;
String userWord = request.getUtterance();
if (StringUtils.isBlank(userId)) return buildTextTaskResult("不好意思好像出了什么问题,正在抓紧修复中", request.getIntentId());
if (StringUtils.isBlank(userWord)) return buildTextTaskResult(Constants.ErrorMsg.SORRY_UNCATCH, request.getIntentId());
Long intentId = request.getIntentId();
if (userWord.contains("晓悟智能小说")) {
RequestTerminal.tmallLunchCancelRequest(userId, type);
return buildTextTaskResult(WELCOME_NOVEL, intentId);
} else if (userWord.contains("晓悟智能故事")) {
RequestTerminal.tmallLunchCancelRequest(userId, type);
return buildTextTaskResult(WELCOME_SMART, intentId);
}
try {
// long start = System.currentTimeMillis();
// log.info("redis get cost:"+(System.currentTimeMillis()-start));
......@@ -113,7 +138,7 @@ public class SpiritRedisService {
}
if (firstIdle) idleNum = "1";
else idleNum = "2";
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 15, TimeUnit.SECONDS);
return buildTextTaskResult((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2, intentId);
} else {
......@@ -129,8 +154,6 @@ public class SpiritRedisService {
} catch (Exception e) {
log.error("tmall redis error:"+e);
}
String userWord = request.getUtterance();
// log.info("天猫精灵用户说的话:"+userWord);
try {
Future<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId));
......@@ -139,10 +162,10 @@ public class SpiritRedisService {
log.error("天猫精灵出现问题:{}", ExceptionUtils.getStackTrace(e));
} catch (TimeoutException e) {
log.warn("超时");
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 20, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
return buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
}
return buildTextTaskResult("不好意思请再说一遍吧", intentId);
return buildTextTaskResult(Constants.ErrorMsg.SORRY_UNCATCH, intentId);
}
private TaskResult requestTerminate(String userId, String userWord, Integer type, Long intentId) throws IOException {
......@@ -163,13 +186,64 @@ public class SpiritRedisService {
default: channelId = "tianmao-jiaoyou-audio-test";
}
headers.put("App-Channel-Id", channelId);
String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
String resStr= OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, headers);
if (resStr == null) {
return null;
}
// log.info("天猫精灵晓悟返回:"+resStr);
TaskResult taskResult = null;
try {
try {
JSONObject object = JSON.parseObject(resStr);
JSONArray commands = object.getJSONArray("commands");
if (commands != null && commands.size() != 0) {
String txt;
for (Object ob: commands) {
txt = ((JSONObject) ob).getString("text");
int i;
if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
log.info("小度,推荐bot退出:{},{}",userWord,userId);
String content = txt.substring(i+3, txt.indexOf("☚")).trim();
String byeWord = null;
String skillName = null;
switch (type) {
case 4: {
byeWord = Constants.EndMsg.XIAOWU_END_BYE_STORY;
skillName = XIAOWU_SKILL_SMART;
break;
}
case 5: {
byeWord = Constants.EndMsg.XIAOWU_END_BYE_NOVEL;
skillName = XIAOWU_SKILL_NOVEL;
break;
}
}
if (byeWord == null) byeWord = Constants.EndMsg.END_BYE_Adult;
if (skillName == null) skillName = SKILL_DEFAULT;
if (StringUtils.isBlank(content)) {
JSONArray dialogs = object.getJSONArray("dialogs");
if (dialogs != null && dialogs.size() != 0) {
String str = ((JSONObject)dialogs.get(0)).getString("text");
if (StringUtils.isNotBlank(str)) {
str = str.replaceAll("\\{/.*?/}", "")+skillName;
RequestTerminal.tmallLunchCancelRequest(userId, type);
return buildTextEndResult(str, intentId);
}
}
RequestTerminal.tmallLunchCancelRequest(userId, type);
return buildTextEndResult(byeWord, intentId);
} else {
content = content.replaceAll("\\{/.*?/}", "")+skillName;
RequestTerminal.tmallLunchCancelRequest(userId, type);
return buildTextEndResult(content, intentId);
}
}
}
}
} catch (Exception e) {
log.error("TMALL 退出解析出错:"+e);
}
final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class);
if (CollectionUtils.isEmpty(response.getDialogs())) {
taskResult = buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
......@@ -183,6 +257,35 @@ public class SpiritRedisService {
} else {
taskResult = buildAudioTaskResult(list, intentId);
}
// if (mark == 1) {
// List<String> list = new ArrayList<>();
// if (manyId == 1) {
// list.add("25715");
// } else if (manyId == 2) {
// list.add("25333");
// list.add("25715");
// } else {
// list.add("25715");
// list.add("25333");
// list.add("25715");
// }
// if (CollectionUtils.isEmpty(list)) {
// StringBuilder builder = new StringBuilder();
// response.getDialogs().forEach(dialog -> builder.append(buildText(dialog.getText())));
// if (builder.length() != 0) taskResult = buildTextTaskResult(builder.toString(), intentId);
// } else {
// taskResult = buildAudioTaskResult(list, intentId);
// }
// } else {
// List<String> list = dealResponse(response, userId, type);
// if (CollectionUtils.isEmpty(list)) {
// StringBuilder builder = new StringBuilder();
// response.getDialogs().forEach(dialog -> builder.append(buildText(dialog.getText())));
// if (builder.length() != 0) taskResult = buildTextTaskResult(builder.toString(), intentId);
// } else {
// taskResult = buildAudioTaskResult(list, intentId);
// }
// }
} catch (Exception e) {
log.error(e.toString());
}
......@@ -206,7 +309,10 @@ public class SpiritRedisService {
if (CollectionUtils.isEmpty(ls)) {
id = InitialData.getRecordId(botAccount, npcName, dialog.getText(), type);
if (StringUtils.isNotBlank(id)) idList.add(id);
else return null;
else {
if (InitialData.botAccount2ItsCache.containsKey(botAccount)) log.warn("没有音频->record:"+dialog);
return null;
}
} else {
idList.addAll(ls);
}
......@@ -217,7 +323,10 @@ public class SpiritRedisService {
if (CollectionUtils.isEmpty(ls)) {
id = InitialData.getAudioId(botAccount, person, mood, dialog.getText(), type);
if (StringUtils.isNotBlank(id)) idList.add(id);
else return null;
else {
if (InitialData.botAccount2ItsCache.containsKey(botAccount)) log.warn("没有音频->audio:"+dialog);
return null;
}
} else {
idList.addAll(ls);
}
......@@ -305,6 +414,14 @@ public class SpiritRedisService {
return result;
}
private TaskResult buildTextEndResult(String text, Long intentId) {
TaskResult result = new TaskResult();
result.setReply(buildText(text));
result.setResultType(ResultType.RESULT);
result.setExecuteCode(ExecuteCode.SUCCESS);
return result;
}
private TaskResult buildAudioTaskResult(List<String> ids, Long intentId) {
TaskResult result = new TaskResult();
result.setReply("叮咚");
......@@ -344,7 +461,7 @@ public class SpiritRedisService {
userId = query.getRequestData().get("deviceOpenId");
}
if (StringUtils.isBlank(userId)) log.error("天猫精灵无法获取到唯一标识的id");
return userId;
return PREFIX_TMALL+userId;
}
public void updateSpiritCsv() {
......@@ -503,4 +620,8 @@ public class SpiritRedisService {
botAccount2ItsCache = botAccount2ItsCacheTemp;
}
}
public static void main(String[] args) {
System.out.println();
}
}
......@@ -18,6 +18,6 @@ import java.util.List;
public class SpiritTerminateResponse {
private String aipioneerUsername;
private List<Dialog> dialogs;
private String extraChatKey;
private String mainChatKey;
// private String extraChatKey;
// private String mainChatKey;
}
package ai.qiwu.com.xiaoduhome.xiaoai.common;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse;
......@@ -55,7 +56,7 @@ public class RequestTerminal {
default: headers = ALL_HEADERS; break;
}
// String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);;
String resStr = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, headers);;
String resStr = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, headers);;
// if (userId.equals(XiaoAiService.deviceId)) {
// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
// }else {
......@@ -69,7 +70,20 @@ public class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttp3Utils.xiaoaiBackPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
OkHttp3Utils.xiaoaiBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
// if (userId.equals(XiaoAiService.deviceId)) {
// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }else {
// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }
}
public static void tmallLunchCancelRequest(String userId, Integer type) {
SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttp3Utils.tmallBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
// if (userId.equals(XiaoAiService.deviceId)) {
// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }else {
......
......@@ -3,6 +3,7 @@ package ai.qiwu.com.xiaoduhome.xiaoai.service;
import ai.qiwu.com.xiaoduhome.common.Constants;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestTerminal;
import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestWordNullException;
......@@ -26,12 +27,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.TTS_DIDI3_GET_XIAOAI;
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.*;
import static ai.qiwu.com.xiaoduhome.service.ScheduleService.jiaoyouChannel2Bots;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
......@@ -230,27 +231,28 @@ public class XiaoAiServiceRedis {
String redisId = SpiritRedisService.PREFIX_REDIS+userId;
try {
// long start = System.currentTimeMillis();
String data = stringRedisTemplate.opsForValue().get(redisId);
// log.info("redis get cost:"+(System.currentTimeMillis()-start));
if (StringUtils.isNotBlank(data)) {
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisId))) {
String data = stringRedisTemplate.opsForValue().get(redisId);
log.info("超时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)) || idleNum.equals("1")) {
try {
Thread.sleep(1000);
Thread.sleep(1500);
} catch (Exception e){}
data = stringRedisTemplate.opsForValue().get(redisId);
if (StringUtils.isNotBlank(data) && !data.equals("out")) {
stringRedisTemplate.delete(redisIdleId);
stringRedisTemplate.delete(redisId);
return buildAudioResponse(changeAudioUrl(data, userId));
}
// data = stringRedisTemplate.opsForValue().get(redisId);
// if (!data.equals("out")) {
// stringRedisTemplate.delete(redisIdleId);
// stringRedisTemplate.delete(redisId);
// return buildAudioResponse(changeAudioUrl(data, userId));
// }
if (firstIdle) idleNum = "1";
else idleNum = "2";
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 15, TimeUnit.SECONDS);
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2);
} else {
......@@ -258,11 +260,12 @@ public class XiaoAiServiceRedis {
stringRedisTemplate.delete(redisId);
}
} else {
stringRedisTemplate.delete(redisIdleId);
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisIdleId))) stringRedisTemplate.delete(redisIdleId);
stringRedisTemplate.delete(redisId);
return buildAudioResponse(changeAudioUrl(data, userId));
}
}
}
} catch (Exception e) {
log.error("xiaoai redis error:"+e);
}
......@@ -284,8 +287,8 @@ public class XiaoAiServiceRedis {
log.error("获取任务执行结果出错:{}", e.toString());
return buildTextResponse(SORRY_REPEAT);
} catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString());
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 10, TimeUnit.SECONDS);
log.info("超时,让用户再说一遍");
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
return buildTextResponse(XiaoAiConstants.ERROR_MSG.TIME_OUT);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", all.toString());
......@@ -345,7 +348,7 @@ public class XiaoAiServiceRedis {
String response;
try {
response = RequestTerminal.requestTerminate(userId, userWord, type);
log.info("小爱,小悟返回:{}", response);
// log.info("小爱,小悟返回:{}", response);
} catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString());
return buildTextResponse(SORRY_REPEAT);
......@@ -408,14 +411,16 @@ public class XiaoAiServiceRedis {
String path;
try {
// path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", response);
if (StringUtils.isBlank(path) || path.equals("null")) {
log.error("没有获取到TTS返回的路径path");
return buildTextResponse(SORRY_REPEAT);
}
xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
log.info("Redis 写入:"+path);
stringRedisTemplate.opsForValue().set(SpiritRedisService.PREFIX_REDIS+userId, path, 10, TimeUnit.SECONDS);
if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
.setIfPresent(SpiritRedisService.PREFIX_REDIS+userId, path, 15, TimeUnit.SECONDS))) {
log.info("xiaoai 超时redis存储成功");
}
// LAST_AUDIO_PLAY.put(userId, path);
} catch (Exception e) {
log.error("没有获取到TTS返回的路径path");
......@@ -426,13 +431,23 @@ public class XiaoAiServiceRedis {
}
private String changeAudioUrl(String path, String userId) {
path = path.replaceAll("%2F", "/");
// path = path.replaceAll("%2F", "/");
// return new StringBuilder(TTS_DIDI3_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
return new StringBuilder("http://didi-gz5.jiaoyou365.com:9663/api/audio/get?type=").append(userId).append("&path=").append(path).toString();
return new StringBuilder(ScheduleServiceNew.BASE_HOST_URL).append("9663/api/audio/get?type=").append(userId).append("&path=").append(path).toString();
}
public void theAudioAlreadyPlay(String userId) {
try {
userId = URLEncoder.encode(userId, "UTF-8");
} catch (Exception e){
log.warn("theAudioAlreadyPlay encode userId failed");
userId = URLEncoder.encode(userId);
}
Boolean result = stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+userId);
log.info("回调删除:"+result);
}
public static void main(String[] args) throws UnsupportedEncodingException {
System.out.println(URLEncoder.encode("XIAOAI_ScfTGmNbhns8KXMJfZY4nQ==", "UTF-8"));
}
}
......@@ -634,6 +634,6 @@ public class XiaoAiTestService {
public static void main(String[] args) throws UnsupportedEncodingException {
XiaoAiTestService service = new XiaoAiTestService();
System.out.println(JSON.toJSONString(service.dealWithLaunchRequestPhone2()));
System.out.println(JSON.toJSONString(service.dealWithLaunchRequestPhone()));
}
}
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