LiveRoomServiceImpl.java 9.9 KB

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