LiveRoomServiceImpl.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package com.ym.service.Impl;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  4. import com.ym.http.HttpHelper;
  5. import com.ym.mec.biz.dal.entity.ImLiveRoomVideo;
  6. import com.ym.mec.biz.service.ImLiveRoomVideoService;
  7. import com.ym.mec.common.entity.ImRoomMessage;
  8. import com.ym.mec.common.exception.BizException;
  9. import com.ym.mec.im.IMHelper;
  10. import com.ym.pojo.IMApiResultInfo;
  11. import com.ym.pojo.IMUserOnlineInfo;
  12. import com.ym.pojo.RecordConfig;
  13. import com.ym.pojo.RecordNotify;
  14. import com.ym.service.LiveRoomService;
  15. import lombok.extern.slf4j.Slf4j;
  16. import org.apache.commons.lang.StringUtils;
  17. import org.redisson.api.RBucket;
  18. import org.redisson.api.RedissonClient;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.stereotype.Service;
  21. import java.net.HttpURLConnection;
  22. import java.util.*;
  23. import java.util.concurrent.TimeUnit;
  24. /**
  25. * @author hgw
  26. * Created by 2022-02-21
  27. */
  28. @Slf4j
  29. @Service
  30. public class LiveRoomServiceImpl implements LiveRoomService {
  31. @Autowired
  32. private IMHelper imHelper;
  33. @Autowired
  34. private HttpHelper httpHelper;
  35. @Autowired
  36. private RedissonClient redissonClient;
  37. @Autowired
  38. private ImLiveRoomVideoService imLiveRoomVideoService;
  39. /**
  40. * 创建房间-聊天室
  41. *
  42. * @param roomId 房间Uid
  43. * @param roomName 房间名称
  44. */
  45. public IMApiResultInfo createLiveRoom(String roomId, String roomName) {
  46. IMApiResultInfo resultInfo;
  47. try {
  48. resultInfo = imHelper.createChatRoom(roomId, roomName);
  49. } catch (Exception e) {
  50. log.error("create chatRoom error >>>", e.getCause());
  51. throw new BizException("创建聊天室失败!");
  52. }
  53. if (!resultInfo.isSuccess()) {
  54. log.error("create chatRoom error: {}", resultInfo.getErrorMessage());
  55. throw new BizException("创建聊天室失败!");
  56. }
  57. log.info("create chatRoom success: {}", roomId);
  58. return resultInfo;
  59. }
  60. /**
  61. * 销毁房间-聊天室
  62. *
  63. * @param roomId 房间Uid
  64. */
  65. public IMApiResultInfo destroyLiveRoom(String roomId) {
  66. //删除服务器房间
  67. List<String> deleteRoomIds = new ArrayList<String>() {{
  68. add(roomId);
  69. }};
  70. IMApiResultInfo resultInfo;
  71. try {
  72. resultInfo = imHelper.deleteChrm(deleteRoomIds);
  73. } catch (Exception e) {
  74. throw new BizException("关闭聊天室失败!");
  75. }
  76. if (!resultInfo.isSuccess()) {
  77. log.error("destroy chatRoom error: {}", resultInfo.getErrorMessage());
  78. throw new BizException("关闭聊天室失败!");
  79. }
  80. return resultInfo;
  81. }
  82. /**
  83. * 发送消息
  84. *
  85. * @param message
  86. */
  87. public IMApiResultInfo publishRoomMessage(ImRoomMessage message) {
  88. log.info("publishRoomMessage message : {}", JSONObject.toJSONString(message));
  89. IMApiResultInfo resultInfo;
  90. try {
  91. resultInfo = imHelper.publishRoomMessage(message.getFromUserId(), message.getToChatroomId(), message);
  92. } catch (Exception e) {
  93. throw new BizException("消息发送失败" + e.getMessage());
  94. }
  95. if (!resultInfo.isSuccess()) {
  96. log.error("publishRoomMessage chatRoom error: {}", resultInfo.getErrorMessage());
  97. throw new BizException("消息发送失败!");
  98. }
  99. return resultInfo;
  100. }
  101. @Override
  102. public void startRecord(String roomId) throws Exception {
  103. log.error("开始录制直播:roomId : {} ", roomId);
  104. JSONObject paramJson = new JSONObject();
  105. paramJson.put("sessionId", getRoomSessionId(roomId));
  106. paramJson.put("config", new RecordConfig());
  107. String body = paramJson.toJSONString();
  108. HttpURLConnection conn = httpHelper.createIMRtcPostHttpConnection("/rtc/record/start.json", "application/json", roomId);
  109. httpHelper.setBodyParameter(body, conn);
  110. String returnResult = httpHelper.returnResult(conn, body);
  111. JSONObject resultObject = JSONObject.parseObject(returnResult);
  112. String code = resultObject.getString("code");
  113. if (!"200".equals(code)) {
  114. log.error("直播视频录制失败:resultInfo : {} ", returnResult);
  115. }
  116. String recordId = resultObject.getString("recordId");
  117. ImLiveRoomVideo video = imLiveRoomVideoService.getOne(new QueryWrapper<ImLiveRoomVideo>().eq("room_uid_", roomId).eq("record_id_", recordId).eq("type", 0));
  118. if (Objects.nonNull(video)) {
  119. return;
  120. }
  121. imLiveRoomVideoService.save(initImLiveRoomVideo(roomId, recordId, new Date()));
  122. }
  123. private ImLiveRoomVideo initImLiveRoomVideo(String roomId, String recordId, Date now) {
  124. ImLiveRoomVideo video = new ImLiveRoomVideo();
  125. video.setRoomUid(roomId);
  126. video.setRecordId(recordId);
  127. video.setStartTime(now);
  128. video.setType(0);
  129. video.setCreatedTime(now);
  130. return video;
  131. }
  132. @Override
  133. public void stopRecord(String roomId) throws Exception {
  134. JSONObject paramJson = new JSONObject();
  135. paramJson.put("sessionId", getRoomSessionId(roomId));
  136. String body = paramJson.toJSONString();
  137. HttpURLConnection conn = httpHelper.createIMRtcPostHttpConnection("/rtc/record/stop.json", "application/json", roomId);
  138. httpHelper.setBodyParameter(body, conn);
  139. redissonClient.getBucket("sessionId:" + roomId).delete();
  140. log.info("结束录制直播 roomId :{},{}", roomId, httpHelper.returnResult(conn, body));
  141. }
  142. @Override
  143. public void recordSync(RecordNotify recordNotify) {
  144. if (recordNotify.getCode().equals(200)) {
  145. if (Objects.nonNull(recordNotify.getType()) && recordNotify.getType() == 4) {
  146. //云端录制文件地址
  147. String fileUrl = recordNotify.getOutput().getFileUrl();
  148. String roomId = recordNotify.getRoomId();
  149. //写入数据库
  150. try {
  151. Date now = new Date();
  152. //获取最后一次录制视频
  153. ImLiveRoomVideo video = imLiveRoomVideoService.getDao().getLastRecord(roomId, recordNotify.getRecordId());
  154. if (Objects.isNull(video)) {
  155. log.error("获取录制视频失败:roomId : {} ,recordId:{}", roomId, recordNotify.getRecordId());
  156. return;
  157. }
  158. if (StringUtils.isNotEmpty(video.getUrl())) {
  159. //保存切片
  160. ImLiveRoomVideo imLiveRoomVideo = initImLiveRoomVideo(roomId, recordNotify.getRecordId(), now);
  161. imLiveRoomVideo.setStartTime(video.getEndTime());
  162. imLiveRoomVideo.setEndTime(now);
  163. imLiveRoomVideo.setUrl(fileUrl);
  164. imLiveRoomVideo.setType(2);
  165. imLiveRoomVideoService.save(imLiveRoomVideo);
  166. return;
  167. } else {
  168. video.setEndTime(now);
  169. video.setType(2);
  170. video.setUrl(fileUrl);
  171. video.setCreatedTime(now);
  172. imLiveRoomVideoService.updateById(video);
  173. }
  174. } catch (Exception e) {
  175. log.error("recordSync >>>> error : {}", e.getMessage());
  176. }
  177. }
  178. }
  179. }
  180. /**
  181. * 查询用户是否在聊天室
  182. *
  183. * @param chatroomId 要查询的聊天室 ID(必传)
  184. * @param userId 要查询的用户 ID(必传)
  185. * @return true 在聊天室,false 不在聊天室
  186. * <p>触发融云退出聊天室机制将用户踢出
  187. * <p>聊天室中用户在离线 30 秒后有新消息产生时或离线后聊天室中产生 30 条消息时会被自动退出聊天室
  188. * <p>此状态需要聊天室中有新消息时才会进行同步
  189. */
  190. public boolean userExistInRoom(String chatroomId, String userId) {
  191. log.info("userExistInRoom chatroomId : {} userId : {}", chatroomId, userId);
  192. IMApiResultInfo resultInfo;
  193. try {
  194. resultInfo = imHelper.isInChartRoom(chatroomId, userId);
  195. } catch (Exception e) {
  196. throw new BizException("查询失败" + e.getMessage());
  197. }
  198. if (!resultInfo.isSuccess()) {
  199. log.error("userExistInRoom chatroomId : {} userId : {}", chatroomId, userId);
  200. throw new BizException("查询失败!");
  201. }
  202. return resultInfo.isSuccess() && resultInfo.getIsInChrm();
  203. }
  204. /**
  205. * 查询用户是否在线
  206. * 注意:断网时,用户状态返回可能不准确
  207. *
  208. * @param userId 要查询的用户 ID(必传)
  209. * @return true 在线,false 不在线
  210. */
  211. public boolean checkOnline(String userId) {
  212. log.info("checkOnline userId : {}", userId);
  213. IMUserOnlineInfo resultInfo;
  214. try {
  215. resultInfo = imHelper.checkOnline(userId);
  216. } catch (Exception e) {
  217. return false;
  218. }
  219. if (!resultInfo.isSuccess()) {
  220. log.error("checkOnline userId : {}", userId);
  221. return false;
  222. }
  223. log.info("checkOnline userId : {} resultInfo code:{} status: {}", userId, resultInfo.getCode(), resultInfo.getStatus());
  224. return Objects.equals("1", resultInfo.getStatus());
  225. }
  226. public String getRoomSessionId(String roomId) {
  227. RBucket<String> bucket = redissonClient.getBucket("sessionId:" + roomId);
  228. if (bucket.isExists()) {
  229. return bucket.get();
  230. }
  231. HttpURLConnection conn;
  232. JSONObject resultObject;
  233. try {
  234. JSONObject jsonObject = new JSONObject();
  235. jsonObject.put("roomId", roomId);
  236. conn = httpHelper.createIMRtcPostHttpConnection("/rtc/room/query.json", "application/json", null);
  237. httpHelper.setBodyParameter(jsonObject.toJSONString(), conn);
  238. String returnResult = httpHelper.returnResult(conn, jsonObject.toJSONString());
  239. resultObject = JSONObject.parseObject(returnResult);
  240. } catch (Exception e) {
  241. throw new BizException("获取sessionId失败", e.getCause());
  242. }
  243. String sessionId;
  244. if ("200".equals(resultObject.getString("code"))) {
  245. sessionId = resultObject.getString("sessionId");
  246. bucket.set(sessionId, 1, TimeUnit.HOURS);
  247. log.info("getRoomSessionId roomId : {} sessionId : {}", roomId, sessionId);
  248. } else {
  249. log.error("获取sessionId失败 roomId : {} returnResult:{}", roomId, resultObject);
  250. throw new BizException("获取sessionId失败");
  251. }
  252. return sessionId;
  253. }
  254. }