package com.qiwu.chatbotbackend.processing; import com.alibaba.fastjson.JSON; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.task.utils.FileFinder; import javax.servlet.ServletContext; import java.io.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static com.qiwu.chatbotbackend.Config.Config.CHATCACHE_TIME_OUT; public class ChatCacheController { public static String CHAT_CACHE_DIR = "ChatCache/"; private static String ARCHIVE_NAME = "%s-%s-%s"; private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; private static String ENV_POSTFIX = "-env.data"; private static String INFO_POSTFIX = "-info.data"; public static String COMBINE_PUNC1 = "@@@"; //chatKey的连接符 chatKey格式为 用户名@@@bot账号@@@@随机码 public static String COMBINE_PUNC2 = "@@@@"; /** * 通过chat_key获得后台保存的历史信息点 * chatCache:存储了chatKye相对应的对话记录(历史信息点) * * @return 历史信息点,对话过程中引擎提取的用户信息 */ public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, String botType) throws Exception { Map chatCacheMap = null; ChatCache chatCache = null; if (context.getAttribute("chatCache") == null) { chatCacheMap = new HashMap(); context.setAttribute("chatCache", chatCacheMap); } else { chatCacheMap = (Map) context.getAttribute("chatCache"); } chatCache = chatCacheMap.get(userKey); //如果用户之前没有玩过或者有一段时间没有玩 if(chatCache == null){ chatCache = new ChatCache(userinfo, userKey, randKey, botType); chatCacheMap.put(userKey, chatCache); //用户几分钟前还在玩 } else { if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { ChatCacheController.saveChatCache(chatCache, null); } chatCache = new ChatCache(userinfo, userKey, randKey, botType); chatCacheMap.put(userKey, chatCache); } } System.out.println(chatCache.getGameEnv()); return chatCache; } public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String nowTime = now .format(format), userId, botAccount, keyElem[]; Boolean opFlag, destroy = false; if(!chatCache.isGameStart() || chatCache.getUserKey().equals(chatCache.getRandKey())) return true; System.out.println("游戏存档中"); String userKey = chatCache.getUserKey(); String site = chatCache.getInfoPoint().get("site"); String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); try { if(helper == null){ helper = new SqlHelper(); destroy = true; } File dir = new File(CHAT_CACHE_DIR); if (!dir.exists()) dir.mkdir(); ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); FileWriter fw = new FileWriter(file); String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); fw.write(jsonString); fw.close(); opFlag = helper.insertArchiveInfo(archiveName, userKey, site); if(destroy) helper.destroy(); } catch (Exception e) { System.out.println("游戏存档时发生异常"); opFlag = false; } return opFlag; } public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { ChatCache chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; System.out.println(archiveInfo.getArchiveId()); String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); keys[1] = keys[1].split("-")[0]; String fileDir = System.getProperty("user.dir") + "/ChatCache"; String line, pair[]; Map infoPoints = new HashMap(); File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); if (file.exists()){ gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); }else{ throw new IOException("环境存档不存在"); } file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String jsonStr = br.readLine(); infoPoint = (Map)JSON.parseObject(jsonStr); chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); chatCache.setGameStart(true); br.close(); fr.close(); return chatCache; } /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo){ String sessionKey; ChatCache chatCache = null; SqlHelper helper = null; long lastChatTime, now; Map history = new HashMap(); Map chatCacheMap = (Map) context.getAttribute("chatCache"); try { helper = new SqlHelper(); Iterator it = chatCacheMap.keySet().iterator(); while (it.hasNext()) { sessionKey = it.next(); if (sessionKey.equals(userKey)) { // saveChatCache(chatCacheMap.get(sessionKey),null); continue; } history = chatCacheMap.get(sessionKey).getInfoPoint(); lastChatTime = Long.valueOf(history.get("lastUpdateTime")); now = System.currentTimeMillis(); if (now - lastChatTime > CHATCACHE_TIME_OUT) { chatCache = chatCacheMap.get(sessionKey); if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { saveChatCache(chatCache, helper); } System.out.println("移除" + sessionKey); it.remove(); } } }catch (Exception e){ e.printStackTrace(); }finally { helper.destroy(); } context.setAttribute("chatCache", chatCacheMap); } /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ public static synchronized void updateChatCache4Insert(Map curInfoPoint, ChatCache chatCache, ServletContext context, UserInfo userInfo) { chatCache.getInfoPoint().put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); Map keyCacheMap = (Map) context.getAttribute("chatCache"); keyCacheMap.put(chatCache.getUserKey(), chatCache); //ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); //chatCache.setInfoPoint(historyInfoPoint); //chatCache.setGameEnv(gameEnv); System.out.println(chatCache.getUserKey()); context.setAttribute("chatCache", keyCacheMap); } public static synchronized boolean findChatCache(String userKey, ServletContext context) throws Exception { ArchiveInfo archiveInfo = null; Map chatCacheMap = null; ChatCache chatCache = null; String fileDir = System.getProperty("user.dir") + "/ChatCache"; Boolean findFlag = false; SqlHelper helper; Map infoPoints = new HashMap(); try { helper = new SqlHelper(); if (context.getAttribute("chatCache") != null) { chatCacheMap = (HashMap)context.getAttribute("chatCache"); System.out.println("context:" + userKey); if (chatCacheMap.containsKey(userKey)) { System.out.println("contain:" + userKey); chatCache = chatCacheMap.get(userKey); // //保存到本地,并从chatCacheMap中删除 if(!chatCache.getUserKey().endsWith(chatCache.getRandKey()) && chatCache.isGameStart()){ findFlag = true; saveChatCache(chatCache, helper); chatCacheMap.remove(userKey); System.out.println("save:" + userKey); } } } if (!findFlag) { System.out.println("sql:" + userKey); archiveInfo = helper.queryUserLastGameArchive(userKey); helper.destroy(); findFlag = (archiveInfo != null); } } catch (Exception e) { e.printStackTrace(); findFlag = false; } System.out.println("finalFlag" + findFlag); return findFlag; } public static Boolean deleteChatCache(SqlHelper helper, String botAccount, ServletContext context){ Map chatCacheMap = null; String userKey = ""; Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount); if (context.getAttribute("chatCache") != null) { chatCacheMap = (HashMap) context.getAttribute("chatCache"); Iterator iter = chatCacheMap.keySet().iterator(); while (iter.hasNext()) { userKey = iter.next(); if (userKey.endsWith(botAccount)) { iter.remove(); } } } Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount); return sqlDeleteFlag && fileDeleteFlag; } }