LiveRoomServiceImpl.java 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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.redisson.api.RBucket;
  16. import org.redisson.api.RedissonClient;
  17. import org.springframework.beans.factory.annotation.Autowired;
  18. import org.springframework.stereotype.Service;
  19. import java.net.HttpURLConnection;
  20. import java.util.ArrayList;
  21. import java.util.Date;
  22. import java.util.List;
  23. import java.util.Objects;
  24. import java.util.concurrent.TimeUnit;
  25. /**
  26. * @author hgw
  27. * Created by 2022-02-21
  28. */
  29. @Slf4j
  30. @Service
  31. public class LiveRoomServiceImpl implements LiveRoomService {
  32. @Autowired
  33. private IMHelper imHelper;
  34. @Autowired
  35. private HttpHelper httpHelper;
  36. @Autowired
  37. private RedissonClient redissonClient;
  38. @Autowired
  39. private ImLiveRoomVideoService imLiveRoomVideoService;
  40. /**
  41. * 创建房间-聊天室
  42. *
  43. * @param roomId 房间Uid
  44. * @param roomName 房间名称
  45. */
  46. public IMApiResultInfo createLiveRoom(String roomId, String roomName) {
  47. IMApiResultInfo resultInfo;
  48. try {
  49. resultInfo = imHelper.createChatRoom(roomId, roomName);
  50. } catch (Exception e) {
  51. log.error("create chatRoom error >>>", e.getCause());
  52. throw new BizException("创建聊天室失败!");
  53. }
  54. if (!resultInfo.isSuccess()) {
  55. log.error("create chatRoom error: {}", resultInfo.getErrorMessage());
  56. throw new BizException("创建聊天室失败!");
  57. }
  58. log.info("create chatRoom success: {}", roomId);
  59. return resultInfo;
  60. }
  61. /**
  62. * 销毁房间-聊天室
  63. *
  64. * @param roomId 房间Uid
  65. */
  66. public IMApiResultInfo destroyLiveRoom(String roomId) {
  67. //删除服务器房间
  68. List<String> deleteRoomIds = new ArrayList<String>() {{
  69. add(roomId);
  70. }};
  71. IMApiResultInfo resultInfo;
  72. try {
  73. resultInfo = imHelper.deleteChrm(deleteRoomIds);
  74. } catch (Exception e) {
  75. throw new BizException("关闭聊天室失败!");
  76. }
  77. if (!resultInfo.isSuccess()) {
  78. log.error("destroy chatRoom error: {}", resultInfo.getErrorMessage());
  79. throw new BizException("关闭聊天室失败!");
  80. }
  81. return resultInfo;
  82. }
  83. /**
  84. * 发送消息
  85. *
  86. * @param message
  87. */
  88. public IMApiResultInfo publishRoomMessage(ImRoomMessage message) {
  89. log.info("publishRoomMessage message : {}", JSONObject.toJSONString(message));
  90. IMApiResultInfo resultInfo;
  91. try {
  92. resultInfo = imHelper.publishRoomMessage(message.getFromUserId(), message.getToChatroomId(), message);
  93. } catch (Exception e) {
  94. throw new BizException("消息发送失败" + e.getMessage());
  95. }
  96. if (!resultInfo.isSuccess()) {
  97. log.error("publishRoomMessage chatRoom error: {}", resultInfo.getErrorMessage());
  98. throw new BizException("消息发送失败!");
  99. }
  100. return resultInfo;
  101. }
  102. @Override
  103. public void startRecord(String roomId) throws Exception {
  104. log.error("开始录制直播:roomId : {} ", roomId);
  105. JSONObject paramJson = new JSONObject();
  106. paramJson.put("sessionId", getRoomSessionId(roomId));
  107. paramJson.put("config", new RecordConfig());
  108. String body = paramJson.toJSONString();
  109. HttpURLConnection conn = httpHelper.createIMRtcPostHttpConnection("/rtc/record/start.json", "application/json", roomId);
  110. httpHelper.setBodyParameter(body, conn);
  111. String returnResult = httpHelper.returnResult(conn, body);
  112. JSONObject resultObject = JSONObject.parseObject(returnResult);
  113. String code = resultObject.getString("code");
  114. if (!"200".equals(code)) {
  115. log.error("直播视频录制失败:resultInfo : {} ", returnResult);
  116. }
  117. String recordId = resultObject.getString("recordId");
  118. ImLiveRoomVideo video = imLiveRoomVideoService.getOne(new QueryWrapper<ImLiveRoomVideo>()
  119. .eq("room_uid_", roomId)
  120. .eq("record_id_", recordId)
  121. .eq("type", 0));
  122. if (Objects.nonNull(video)) {
  123. return;
  124. } else {
  125. video = new ImLiveRoomVideo();
  126. }
  127. video.setRoomUid(roomId);
  128. video.setRecordId(recordId);
  129. video.setStartTime(new Date());
  130. video.setType(0);
  131. video.setCreatedTime(new Date());
  132. imLiveRoomVideoService.save(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. ImLiveRoomVideo video = imLiveRoomVideoService.getOne(new QueryWrapper<ImLiveRoomVideo>()
  154. .eq("room_uid_", roomId)
  155. .eq("record_id_", recordNotify.getRecordId())
  156. .eq("type", 0));
  157. if (Objects.isNull(video)) {
  158. return;
  159. }
  160. Date now = new Date();
  161. video.setEndTime(now);
  162. video.setType(2);
  163. video.setUrl(fileUrl);
  164. video.setCreatedTime(now);
  165. imLiveRoomVideoService.updateById(video);
  166. } catch (Exception e) {
  167. log.error("recordSync >>>> error : {}", e.getMessage());
  168. }
  169. }
  170. }
  171. }
  172. /**
  173. * 查询用户是否在聊天室
  174. *
  175. * @param chatroomId 要查询的聊天室 ID(必传)
  176. * @param userId 要查询的用户 ID(必传)
  177. * @return true 在聊天室,false 不在聊天室
  178. */
  179. public boolean userExistInRoom(String chatroomId, String userId) {
  180. log.info("userExistInRoom chatroomId : {} userId : {}", chatroomId, userId);
  181. IMApiResultInfo resultInfo;
  182. try {
  183. resultInfo = imHelper.isInChartRoom(chatroomId, userId);
  184. } catch (Exception e) {
  185. throw new BizException("查询失败" + e.getMessage());
  186. }
  187. if (!resultInfo.isSuccess()) {
  188. log.error("userExistInRoom chatroomId : {} userId : {}", chatroomId, userId);
  189. throw new BizException("查询失败!");
  190. }
  191. return resultInfo.isSuccess() && resultInfo.getIsInChrm();
  192. }
  193. public String getRoomSessionId(String roomId) {
  194. RBucket<String> bucket = redissonClient.getBucket("sessionId:" + roomId);
  195. if (bucket.isExists()) {
  196. return bucket.get();
  197. }
  198. HttpURLConnection conn;
  199. JSONObject resultObject;
  200. try {
  201. JSONObject jsonObject = new JSONObject();
  202. jsonObject.put("roomId", roomId);
  203. conn = httpHelper.createIMRtcPostHttpConnection("/rtc/room/query.json", "application/json", null);
  204. httpHelper.setBodyParameter(jsonObject.toJSONString(), conn);
  205. String returnResult = httpHelper.returnResult(conn, jsonObject.toJSONString());
  206. resultObject = JSONObject.parseObject(returnResult);
  207. } catch (Exception e) {
  208. throw new BizException("获取sessionId失败", e.getCause());
  209. }
  210. String sessionId;
  211. if ("200".equals(resultObject.getString("code"))) {
  212. sessionId = resultObject.getString("sessionId");
  213. bucket.set(sessionId, 1, TimeUnit.HOURS);
  214. log.info("getRoomSessionId roomId : {} sessionId : {}", roomId, sessionId);
  215. } else {
  216. log.error("获取sessionId失败 roomId : {} returnResult:{}", roomId, resultObject);
  217. throw new BizException("获取sessionId失败");
  218. }
  219. return sessionId;
  220. }
  221. }