LiveRoomServiceImpl.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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, String videoResolution) throws Exception {
  103. log.error("开始录制直播:roomId : {} ", roomId);
  104. JSONObject paramJson = new JSONObject();
  105. paramJson.put("sessionId", getRoomSessionId(roomId));
  106. RecordConfig recordConfig = new RecordConfig();
  107. Optional.ofNullable(videoResolution)
  108. .ifPresent(recordConfig::setVideoResolution);
  109. paramJson.put("config", recordConfig);
  110. String body = paramJson.toJSONString();
  111. HttpURLConnection conn = httpHelper.createIMRtcPostHttpConnection("/rtc/record/start.json", "application/json", roomId);
  112. httpHelper.setBodyParameter(body, conn);
  113. String returnResult = httpHelper.returnResult(conn, body);
  114. JSONObject resultObject = JSONObject.parseObject(returnResult);
  115. String code = resultObject.getString("code");
  116. if (!"200".equals(code)) {
  117. log.error("直播视频录制失败:resultInfo : {} ", returnResult);
  118. }
  119. String recordId = resultObject.getString("recordId");
  120. ImLiveRoomVideo video = imLiveRoomVideoService.getOne(new QueryWrapper<ImLiveRoomVideo>().eq("room_uid_", roomId).eq("record_id_", recordId).eq("type", 0));
  121. if (Objects.nonNull(video)) {
  122. return;
  123. }
  124. imLiveRoomVideoService.save(initImLiveRoomVideo(roomId, recordId, new Date()));
  125. }
  126. private ImLiveRoomVideo initImLiveRoomVideo(String roomId, String recordId, Date now) {
  127. ImLiveRoomVideo video = new ImLiveRoomVideo();
  128. video.setRoomUid(roomId);
  129. video.setRecordId(recordId);
  130. video.setStartTime(now);
  131. video.setType(0);
  132. video.setCreatedTime(now);
  133. return video;
  134. }
  135. @Override
  136. public void stopRecord(String roomId) throws Exception {
  137. JSONObject paramJson = new JSONObject();
  138. paramJson.put("sessionId", getRoomSessionId(roomId));
  139. String body = paramJson.toJSONString();
  140. HttpURLConnection conn = httpHelper.createIMRtcPostHttpConnection("/rtc/record/stop.json", "application/json", roomId);
  141. httpHelper.setBodyParameter(body, conn);
  142. redissonClient.getBucket("sessionId:" + roomId).delete();
  143. log.info("结束录制直播 roomId :{},{}", roomId, httpHelper.returnResult(conn, body));
  144. }
  145. @Override
  146. public void recordSync(RecordNotify recordNotify) {
  147. if (recordNotify.getCode().equals(200)) {
  148. if (Objects.nonNull(recordNotify.getType()) && recordNotify.getType() == 4) {
  149. //云端录制文件地址
  150. String fileUrl = recordNotify.getOutput().getFileUrl();
  151. String roomId = recordNotify.getRoomId();
  152. //写入数据库
  153. try {
  154. Date now = new Date();
  155. //获取最后一次录制视频
  156. ImLiveRoomVideo video = imLiveRoomVideoService.getDao().getLastRecord(roomId, recordNotify.getRecordId());
  157. if (Objects.isNull(video)) {
  158. log.error("获取录制视频失败:roomId : {} ,recordId:{}", roomId, recordNotify.getRecordId());
  159. return;
  160. }
  161. if (StringUtils.isNotEmpty(video.getUrl())) {
  162. //保存切片
  163. ImLiveRoomVideo imLiveRoomVideo = initImLiveRoomVideo(roomId, recordNotify.getRecordId(), now);
  164. imLiveRoomVideo.setStartTime(video.getEndTime());
  165. imLiveRoomVideo.setEndTime(now);
  166. imLiveRoomVideo.setUrl(fileUrl);
  167. imLiveRoomVideo.setType(2);
  168. imLiveRoomVideoService.save(imLiveRoomVideo);
  169. return;
  170. } else {
  171. video.setEndTime(now);
  172. video.setType(2);
  173. video.setUrl(fileUrl);
  174. video.setCreatedTime(now);
  175. imLiveRoomVideoService.updateById(video);
  176. }
  177. } catch (Exception e) {
  178. log.error("recordSync >>>> error : {}", e.getMessage());
  179. }
  180. }
  181. }
  182. }
  183. /**
  184. * 查询用户是否在聊天室
  185. *
  186. * @param chatroomId 要查询的聊天室 ID(必传)
  187. * @param userId 要查询的用户 ID(必传)
  188. * @return true 在聊天室,false 不在聊天室
  189. * <p>触发融云退出聊天室机制将用户踢出
  190. * <p>聊天室中用户在离线 30 秒后有新消息产生时或离线后聊天室中产生 30 条消息时会被自动退出聊天室
  191. * <p>此状态需要聊天室中有新消息时才会进行同步
  192. */
  193. public boolean userExistInRoom(String chatroomId, String userId) {
  194. log.info("userExistInRoom chatroomId : {} userId : {}", chatroomId, userId);
  195. IMApiResultInfo resultInfo;
  196. try {
  197. resultInfo = imHelper.isInChartRoom(chatroomId, userId);
  198. } catch (Exception e) {
  199. throw new BizException("查询失败" + e.getMessage());
  200. }
  201. if (!resultInfo.isSuccess()) {
  202. log.error("userExistInRoom chatroomId : {} userId : {}", chatroomId, userId);
  203. throw new BizException("查询失败!");
  204. }
  205. return resultInfo.isSuccess() && resultInfo.getIsInChrm();
  206. }
  207. /**
  208. * 查询用户是否在线
  209. * 注意:断网时,用户状态返回可能不准确
  210. *
  211. * @param userId 要查询的用户 ID(必传)
  212. * @return true 在线,false 不在线
  213. */
  214. public boolean checkOnline(String userId) {
  215. log.info("checkOnline userId : {}", userId);
  216. IMUserOnlineInfo resultInfo;
  217. try {
  218. resultInfo = imHelper.checkOnline(userId);
  219. } catch (Exception e) {
  220. return false;
  221. }
  222. if (!resultInfo.isSuccess()) {
  223. log.error("checkOnline userId : {}", userId);
  224. return false;
  225. }
  226. log.info("checkOnline userId : {} resultInfo code:{} status: {}", userId, resultInfo.getCode(), resultInfo.getStatus());
  227. return Objects.equals("1", resultInfo.getStatus());
  228. }
  229. /**
  230. * 添加禁言成员-默认禁言120分钟
  231. *
  232. * @param roomUid 房间uid
  233. * @param userId 用户id
  234. */
  235. public boolean addUserUnableSpeak(String roomUid, String userId) {
  236. log.info("addUserUnableToSpeak chatroomId : {} userId : {}", roomUid, userId);
  237. IMApiResultInfo resultInfo;
  238. try {
  239. resultInfo = imHelper.addUserUnableSpeak(roomUid, userId, "120");
  240. } catch (Exception e) {
  241. log.error("addUserUnableToSpeak chatroomId error: {} userId : {}", roomUid, userId);
  242. return false;
  243. }
  244. if (!resultInfo.isSuccess()) {
  245. log.error("addUserUnableToSpeak chatroomId : {} userId : {}", roomUid, userId);
  246. return false;
  247. }
  248. return true;
  249. }
  250. /**
  251. * 移除禁言成员
  252. *
  253. * @param roomUid 房间uid
  254. * @param userId 用户id
  255. */
  256. public boolean removeUserUnableSpeak(String roomUid, String userId) {
  257. log.info("removeUserUnableSpeak chatroomId : {} userId : {}", roomUid, userId);
  258. IMApiResultInfo resultInfo;
  259. try {
  260. resultInfo = imHelper.removeUserUnableSpeak(roomUid, userId);
  261. } catch (Exception e) {
  262. log.error("removeUserUnableSpeak chatroomId error: {} userId : {}", roomUid, userId);
  263. return false;
  264. }
  265. if (!resultInfo.isSuccess()) {
  266. log.error("removeUserUnableSpeak chatroomId : {} userId : {}", roomUid, userId);
  267. return false;
  268. }
  269. return true;
  270. }
  271. public String getRoomSessionId(String roomId) {
  272. RBucket<String> bucket = redissonClient.getBucket("sessionId:" + roomId);
  273. if (bucket.isExists()) {
  274. return bucket.get();
  275. }
  276. HttpURLConnection conn;
  277. JSONObject resultObject;
  278. try {
  279. JSONObject jsonObject = new JSONObject();
  280. jsonObject.put("roomId", roomId);
  281. conn = httpHelper.createIMRtcPostHttpConnection("/rtc/room/query.json", "application/json", null);
  282. httpHelper.setBodyParameter(jsonObject.toJSONString(), conn);
  283. String returnResult = httpHelper.returnResult(conn, jsonObject.toJSONString());
  284. resultObject = JSONObject.parseObject(returnResult);
  285. } catch (Exception e) {
  286. throw new BizException("获取sessionId失败", e.getCause());
  287. }
  288. String sessionId;
  289. if ("200".equals(resultObject.getString("code"))) {
  290. sessionId = resultObject.getString("sessionId");
  291. bucket.set(sessionId, 1, TimeUnit.HOURS);
  292. log.info("getRoomSessionId roomId : {} sessionId : {}", roomId, sessionId);
  293. } else {
  294. log.error("获取sessionId失败 roomId : {} returnResult:{}", roomId, resultObject);
  295. throw new BizException("获取sessionId失败");
  296. }
  297. return sessionId;
  298. }
  299. }