LiveRoomServiceImpl.java 13 KB

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