package com.izouma.meta.websocket; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.izouma.meta.domain.PublicScreenChat; import com.izouma.meta.dto.PublicScreenChatExceptionMsg; import com.izouma.meta.dto.PurchaseLevelDTO; import com.izouma.meta.dto.WebsocketUser; import com.izouma.meta.exception.BusinessException; import com.izouma.meta.repo.PublicScreenChatRepo; import com.izouma.meta.service.ContentAuditService; import com.izouma.meta.utils.ApplicationContextUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.time.LocalDateTime; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @Service @ServerEndpoint(value = "/websocket/public/screen/{nickName}/{userId}") @Slf4j public class PublicScreenChatWebsocket { /** * 当前在线的客户端map */ private static final Map clients = new ConcurrentHashMap(); private PublicScreenChatRepo publicScreenChatRepo; private final String PREFIX = "meta-chat:"; private ContentAuditService contentAuditService; private WebsocketCommon websocketCommon; private void init() { if (Objects.isNull(publicScreenChatRepo)) { publicScreenChatRepo = (PublicScreenChatRepo) ApplicationContextUtil.getBean("publicScreenChatRepo"); } if (Objects.isNull(contentAuditService)) { contentAuditService = (ContentAuditService) ApplicationContextUtil.getBean("contentAuditService"); } if (Objects.isNull(websocketCommon)) { websocketCommon = (WebsocketCommon) ApplicationContextUtil.getBean("websocketCommon"); } } @OnOpen public void onOpen(@PathParam("nickName") String nickName, @PathParam("userId") String userId, Session session) { init(); // 判断当前玩家是否在其他地方登陆 if (clients.containsKey(PREFIX.concat(userId))) { String msg = String.format("已在别处登陆,sessionId为[%S],正在为您关闭本连接", session.getId()); exceptionHandle(userId, new PublicScreenChatExceptionMsg(1, msg)); try { log.info("关闭session连接"); clients.get(PREFIX.concat(userId)).close(); } catch (Exception e) { exceptionHandle(userId, new PublicScreenChatExceptionMsg(1, String.format("session close throw exception[%S]", e))); return; } } log.info("现在来连接的sessionId:" + session.getId() + "玩家id:" + userId + "玩家昵称" + nickName); clients.put(PREFIX.concat(userId), session); String format = String.format("玩家[%S][%S]进入大厅", userId, nickName); PublicScreenChat publicScreenChat; try { publicScreenChat = savePublicScreenChat(userId, format, true); } catch (Exception e) { String errMsg = String.format("玩家进入大厅,保存信息发生异常[%S]", e); exceptionHandle(userId, new PublicScreenChatExceptionMsg(2, errMsg)); return; } websocketCommon.sendMessageToOther(clients, JSON.toJSONString(publicScreenChat), PREFIX.concat(userId)); } @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); // 异常处理 log.error(String.format("sessionId[%S]的服务端发生了错误:[%S]", session.getId(), error)); } @OnClose public void onClose(@PathParam("nickName") String nickName, @PathParam("userId") String userId, Session session) { init(); log.info(String.format("sessionId:[%S] userId:[%S] is closed", session.getId(), userId)); String format = String.format("玩家[%S][%S]离开大厅", userId, nickName); PublicScreenChat publicScreenChat; try { publicScreenChat = savePublicScreenChat(userId, format, true); } catch (Exception e) { String errMsg = String.format("玩家离开大厅,保存信息发生异常[%S]", e); exceptionHandle(userId, new PublicScreenChatExceptionMsg(2, errMsg)); return; } websocketCommon.sendMessageToOther(clients, JSON.toJSONString(publicScreenChat), PREFIX.concat(userId)); clients.remove(PREFIX.concat(userId)); } @OnMessage public void onMessage(@PathParam("userId") String userId, String message) { init(); if (StringUtils.isBlank(message)) { String errMsg = "Illegal parameter : message can not be null"; exceptionHandle(userId, new PublicScreenChatExceptionMsg(4, errMsg)); return; } log.info(String.format("收到来自userId[%S]的消息[%S]", userId, message)); if (!contentAuditService.auditText(message)) { savePublicScreenChat(userId, message, false); exceptionHandle(userId, new PublicScreenChatExceptionMsg(3, "消息包含非法内容")); return; } PublicScreenChat publicScreenChat; try { publicScreenChat = savePublicScreenChat(userId, message, true); } catch (Exception e) { String errMsg = String.format("玩家发送消息,保存信息发生异常[%S]", e); exceptionHandle(userId, new PublicScreenChatExceptionMsg(2, errMsg)); return; } sendMessageToAll(clients, JSON.toJSONString(publicScreenChat), PREFIX.concat(userId)); } /** * 给所有用户发消息 * * @param clients 在线客户端 * @param message 消息 */ public void sendMessageToAll(Map clients, String message, String userId) { PublicScreenChat publicScreenChat = JSON.parseObject(message, PublicScreenChat.class); Set userIds = clients.keySet(); userIds.forEach(id -> { try { publicScreenChat.setMyself(id.equals(userId)); log.info(String.format("服务器给所有在线用户发送消息,当前在线人员为[%S]。消息:[%S]", id, JSON.toJSONString(publicScreenChat))); clients.get(id).getBasicRemote().sendText(JSON.toJSONString(publicScreenChat)); } catch (Exception e) { log.error(String.format("send message [%S] to [%S] throw exception [%S]:", JSON.toJSONString(publicScreenChat), id, e)); } }); } private PublicScreenChat savePublicScreenChat(String userId, String messageInfo, boolean illegal) { String resultForWebsocketUser = websocketCommon.getRequest("/user/websocket/".concat(userId)); log.info(String.format("userId:[%S] userInfo:[%S]", userId, resultForWebsocketUser)); WebsocketUser websocketUser; try { websocketUser = JSONObject.parseObject(resultForWebsocketUser, WebsocketUser.class); } catch (Exception e) { String errMsg = String.format("WebsocketUser JSON parse throw exception:[%S]", e); log.error(errMsg); throw new BusinessException(errMsg); } if (Objects.isNull(websocketUser)) { String errMsg = "用户信息不存在"; log.error(errMsg); throw new BusinessException(errMsg); } PublicScreenChat publicScreenChat = new PublicScreenChat(); publicScreenChat.setUserId(userId); publicScreenChat.setAvatar(websocketUser.getAvatar()); publicScreenChat.setNickname(websocketUser.getNickname()); publicScreenChat.setLevel(websocketUser.getLevel()); String resultForPurchaseLevel = websocketCommon.getRequest("/purchaseLevel/websocket/".concat(String.valueOf(websocketUser.getLevel()))); log.info(String.format("userId:[%S] purchaseLevelInfo:[%S]", userId, resultForPurchaseLevel)); PurchaseLevelDTO purchaseLevelDTO; try { purchaseLevelDTO = JSONObject.parseObject(resultForPurchaseLevel, PurchaseLevelDTO.class); } catch (Exception e) { String errMsg = String.format("PurchaseLevelDTO JSON parse throw exception:[%S]", e); log.error(errMsg); throw new BusinessException(errMsg); } if (Objects.isNull(purchaseLevelDTO)) { throw new BusinessException("用户等级称号信息不存在"); } publicScreenChat.setRealm(purchaseLevelDTO.getRealm()); publicScreenChat.setTitle(purchaseLevelDTO.getTitle()); publicScreenChat.setMessageInfo(messageInfo); publicScreenChat.setTime(LocalDateTime.now()); publicScreenChat.setIllegal(illegal); return publicScreenChatRepo.save(publicScreenChat); } private void exceptionHandle(String userId, PublicScreenChatExceptionMsg msg) { log.error(JSON.toJSONString(msg)); // 推送消息给该玩家 websocketCommon.sendMessageTo(clients, JSON.toJSONString(msg), PREFIX.concat(userId)); } }