RoomServiceImpl.java 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707
  1. package com.ym.service.Impl;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.serializer.SerializerFeature;
  5. import com.google.common.collect.Lists;
  6. import com.google.common.collect.Maps;
  7. import com.microsvc.toolkit.middleware.rtc.RTCRoomPluginContext;
  8. import com.microsvc.toolkit.middleware.rtc.RTCRoomPluginService;
  9. import com.microsvc.toolkit.middleware.rtc.enums.EMemberAction;
  10. import com.microsvc.toolkit.middleware.rtc.impl.RongCloudRTCPlugin;
  11. import com.microsvc.toolkit.middleware.rtc.impl.TencentCloudRTCPlugin;
  12. import com.microsvc.toolkit.middleware.rtc.message.ImGroupMemberWrapper;
  13. import com.microsvc.toolkit.middleware.rtc.message.RTCRoomMessage;
  14. import com.ym.common.ApiException;
  15. import com.ym.common.BaseResponse;
  16. import com.ym.common.DisplayEnum;
  17. import com.ym.common.ErrorEnum;
  18. import com.ym.config.IMProperties;
  19. import com.ym.config.RoomProperties;
  20. import com.ym.dao.RoomDao;
  21. import com.ym.dao.RoomMemberDao;
  22. import com.ym.dao.UserDao;
  23. import com.ym.dao.WhiteboardDao;
  24. import com.ym.enums.ActionEnum;
  25. import com.ym.enums.DeviceTypeEnum;
  26. import com.ym.enums.RoleEnum;
  27. import com.ym.job.ScheduleManager;
  28. import com.ym.mec.auth.api.client.SysUserFeignService;
  29. import com.ym.mec.auth.api.entity.SysUser;
  30. import com.ym.mec.biz.dal.dao.*;
  31. import com.ym.mec.biz.dal.dto.BasicUserDto;
  32. import com.ym.mec.biz.dal.dto.RongyunBasicUserDto;
  33. import com.ym.mec.biz.dal.entity.*;
  34. import com.ym.mec.biz.dal.enums.GroupType;
  35. import com.ym.mec.biz.dal.enums.TeachModeEnum;
  36. import com.ym.mec.biz.service.*;
  37. import com.ym.mec.common.exception.BizException;
  38. import com.ym.mec.common.page.WrapperUtil;
  39. import com.ym.mec.common.tenant.TenantContextHolder;
  40. import com.ym.mec.im.IMHelper;
  41. import com.ym.mec.im.message.*;
  42. import com.ym.mec.util.collection.MapUtil;
  43. import com.ym.mec.util.date.DateUtil;
  44. import com.ym.pojo.*;
  45. import com.ym.service.RoomService;
  46. import com.ym.utils.CheckUtils;
  47. import com.ym.utils.CodeUtil;
  48. import com.ym.utils.DateTimeUtils;
  49. import com.ym.utils.IdentifierUtils;
  50. import com.ym.whiteboard.WhiteBoardHelper;
  51. import lombok.extern.slf4j.Slf4j;
  52. import org.apache.commons.collections.CollectionUtils;
  53. import org.apache.commons.lang3.StringUtils;
  54. import org.joda.time.DateTime;
  55. import org.joda.time.format.DateTimeFormat;
  56. import org.springframework.beans.factory.annotation.Autowired;
  57. import org.springframework.data.redis.core.RedisTemplate;
  58. import org.springframework.stereotype.Service;
  59. import org.springframework.transaction.annotation.Isolation;
  60. import org.springframework.transaction.annotation.Propagation;
  61. import org.springframework.transaction.annotation.Transactional;
  62. import java.text.MessageFormat;
  63. import java.util.*;
  64. import java.util.concurrent.TimeUnit;
  65. import java.util.function.Function;
  66. import java.util.stream.Collectors;
  67. import static com.ym.enums.RoleEnum.RoleStudent;
  68. import static com.ym.enums.RoleEnum.RoleTeacher;
  69. /**
  70. * Created by super_zou on 2019/11/28.
  71. */
  72. @Slf4j
  73. @Service
  74. public class RoomServiceImpl implements RoomService {
  75. @Autowired
  76. private IMHelper imHelper;
  77. @Autowired
  78. private RoomProperties roomProperties;
  79. @Autowired
  80. private RoomDao roomDao;
  81. @Autowired
  82. private RoomMemberDao roomMemberDao;
  83. @Autowired
  84. private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
  85. @Autowired
  86. private WhiteBoardHelper whiteBoardHelper;
  87. @Autowired
  88. private WhiteboardDao whiteboardDao;
  89. @Autowired
  90. private ScheduleManager scheduleManager;
  91. @Autowired
  92. private UserDao userDao;
  93. @Autowired
  94. private TeacherDao teacherDao;
  95. @Autowired
  96. private CourseScheduleDao courseScheduleDao;
  97. @Autowired
  98. private TeacherAttendanceService teacherAttendanceService;
  99. @Autowired
  100. private StudentAttendanceService studentAttendanceService;
  101. @Autowired
  102. private IMProperties imProperties;
  103. @Autowired
  104. private SysUserFeignService sysUserFeignService;
  105. @Autowired
  106. private SysExamSongDao sysExamSongDao;
  107. @Autowired
  108. private CourseScheduleStudentMusicScoreDao courseScheduleStudentMusicScoreDao;
  109. @Autowired
  110. private SysMusicScoreAccompanimentDao sysMusicScoreAccompanimentDao;
  111. @Autowired
  112. private SysTenantConfigService sysTenantConfigService;
  113. @Autowired
  114. private SysConfigDao sysConfigDao;
  115. @Autowired
  116. private TenantAssetsInfoService tenantAssetsInfoService;
  117. @Autowired
  118. private RedisTemplate<String, String> redisTemplate;
  119. @Autowired
  120. private RTCRoomPluginContext rtcRoomPluginContext;
  121. @Autowired
  122. private VipGroupDao vipGroupDao;
  123. @Autowired
  124. private ImLiveBroadcastRoomService imLiveBroadcastRoomService;
  125. @Override
  126. public Integer getCurrentCourseId(String roomId) {
  127. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(roomId));
  128. //是否是连堂课
  129. String continueCourseTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.ONLINE_CONTINUE_COURSE_TIME, courseSchedule.getTenantId());
  130. if (StringUtils.isEmpty(continueCourseTime)) {
  131. continueCourseTime = "5";
  132. }
  133. CourseSchedule schedule = courseSchedule;
  134. //如果当前课程是连堂课,那么获取第一节课的课程编号
  135. while (true) {
  136. String classDate = DateUtil.format(schedule.getClassDate(), DateUtil.DEFAULT_PATTERN);
  137. String startClassTime = DateUtil.format(schedule.getStartClassTime(), DateUtil.EXPANDED_TIME_FORMAT);
  138. schedule = courseScheduleDao.getFirstCourse(schedule.getClassGroupId(), classDate + " " + startClassTime, schedule.getActualTeacherId(), continueCourseTime);
  139. if (schedule != null) {
  140. roomId = schedule.getId().toString();
  141. } else {
  142. break;
  143. }
  144. }
  145. return Integer.parseInt(roomId);
  146. }
  147. @Transactional(rollbackFor = Exception.class)
  148. public String getCloseNetworkRoomTime(CourseSchedule courseSchedule, String continueCourseTime) {
  149. String autoCloseNetworkRoomTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.COURSE_AFTER_BUFFER_TIME, courseSchedule.getTenantId());
  150. if (StringUtils.isEmpty(autoCloseNetworkRoomTime)) {
  151. autoCloseNetworkRoomTime = "15";
  152. }
  153. CourseSchedule schedule = courseSchedule;
  154. //如果当前课程是连堂课,那么获取第一节课的课程编号
  155. while (true) {
  156. String classDate = DateUtil.format(schedule.getClassDate(), DateUtil.DEFAULT_PATTERN);
  157. String endClassTime = DateUtil.format(schedule.getEndClassTime(), DateUtil.EXPANDED_TIME_FORMAT);
  158. schedule = courseScheduleDao.getLastCourse(schedule.getClassGroupId(), classDate + " " + endClassTime, schedule.getActualTeacherId(), continueCourseTime);
  159. if (schedule != null) {
  160. autoCloseNetworkRoomTime = DateUtil.minutesBetween(new Date(), schedule.getEndClassTime()) + "";
  161. } else {
  162. break;
  163. }
  164. }
  165. return autoCloseNetworkRoomTime;
  166. }
  167. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  168. @Override
  169. public BaseResponse joinRoom(String roomId, Boolean joinRoom) throws Exception {
  170. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  171. SysUser sysUser = sysUserFeignService.queryUserInfo();
  172. String userId = sysUser.getId().toString();
  173. log.info("joinRoom: roomId={}, userId={}", roomId, userId);
  174. Teacher teacher = teacherDao.get(Integer.parseInt(userId));
  175. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(roomId));
  176. if (courseSchedule.getTeachMode() == TeachModeEnum.OFFLINE) {
  177. return new BaseResponse(ErrorEnum.JOIN_ROOM_ERROR, ErrorEnum.JOIN_ROOM_ERROR.getErrMsg(), null);
  178. }
  179. Date curTime = DateTime.now().toDate();
  180. //是否提前进入教室
  181. String courseBeforeBufferTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.COURSE_BEFORE_BUFFER_TIME, courseSchedule.getTenantId());
  182. if (StringUtils.isEmpty(courseBeforeBufferTime)) {
  183. courseBeforeBufferTime = "5";
  184. }
  185. Date addMinutes = DateUtil.addMinutes(curTime, Integer.parseInt(courseBeforeBufferTime));
  186. if (courseSchedule.getStartClassTime().compareTo(addMinutes) > 0) {
  187. return new BaseResponse(ErrorEnum.ROOM_NOT_START, ErrorEnum.ROOM_NOT_START.getErrMsg(), null);
  188. // throw new BizException("网络教室暂未开启,请在{}分钟后进入教室",DateUtil.minutesBetween(addMinutes,courseSchedule.getStartClassTime()));
  189. }
  190. final TenantAssetsInfo one = tenantAssetsInfoService.getOne(new WrapperUtil<TenantAssetsInfo>()
  191. .hasEq("tenant_id_", courseSchedule.getTenantId())
  192. .queryWrapper()
  193. .gt("balance_", 0));
  194. if (one == null) {
  195. return new BaseResponse(ErrorEnum.CLOUD_BALANCE_NOT_FEE, ErrorEnum.CLOUD_BALANCE_NOT_FEE.getErrMsg(), null);
  196. }
  197. //是否是连堂课
  198. String continueCourseTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.ONLINE_CONTINUE_COURSE_TIME, courseSchedule.getTenantId());
  199. if (StringUtils.isEmpty(continueCourseTime)) {
  200. continueCourseTime = "5";
  201. }
  202. RoomResult roomResult = new RoomResult();
  203. // 直播间编号
  204. roomResult.setLiveRoomId(courseSchedule.getLiveRoomId());
  205. roomResult.setAutoCloseNetworkRoomTime(this.getCloseNetworkRoomTime(courseSchedule, continueCourseTime));
  206. CourseSchedule schedule = courseSchedule;
  207. //如果当前课程是连堂课,那么获取第一节课的课程编号
  208. while (true) {
  209. String classDate = DateUtil.format(schedule.getClassDate(), DateUtil.DEFAULT_PATTERN);
  210. String startClassTime = DateUtil.format(schedule.getStartClassTime(), DateUtil.EXPANDED_TIME_FORMAT);
  211. schedule = courseScheduleDao.getFirstCourse(schedule.getClassGroupId(), classDate + " " + startClassTime, schedule.getActualTeacherId(), continueCourseTime);
  212. if (schedule != null) {
  213. roomId = schedule.getId().toString();
  214. // roomResult.setAutoCloseFlag(false);
  215. } else {
  216. break;
  217. }
  218. }
  219. Long courseId = Long.parseLong(roomId);
  220. //记录用户实际选择的房间
  221. if (courseSchedule.getGroupType() == GroupType.COMM) {
  222. roomId = "I" + roomId;
  223. } else {
  224. roomId = "S" + roomId;
  225. }
  226. redisTemplate.opsForValue().setIfAbsent(roomId + userId, courseSchedule.getId().toString());
  227. log.info("joinRoom current: roomId={}, userId={}", roomId, userId);
  228. // 获取RTC服务提供方
  229. if (StringUtils.isBlank(courseSchedule.getServiceProvider())) {
  230. String rtcServiceProvider = Optional.ofNullable(sysConfigDao.findConfigValue(SysConfigService.RTC_SERVICE_PROVIDER))
  231. .orElse(RongCloudRTCPlugin.PLUGIN_NAME);
  232. // 按分部强制开始腾讯网络教室
  233. {
  234. List<Integer> collect = Arrays.stream(Optional.ofNullable(sysConfigDao.findConfigValue(SysConfigService.TENCENT_RTC_SERVICE_PROVIDER)).orElse("").split(","))
  235. .filter(StringUtils::isNotBlank)
  236. .map(Integer::parseInt).distinct().collect(Collectors.toList());
  237. if (collect.contains(courseSchedule.getOrganId())) {
  238. // 强制开启腾讯网络教室
  239. rtcServiceProvider = TencentCloudRTCPlugin.PLUGIN_NAME;
  240. }
  241. }
  242. courseSchedule.setServiceProvider(rtcServiceProvider);
  243. // 更新网络课服务提供方
  244. courseScheduleDao.updateServiceProvider(courseSchedule.getId(), courseSchedule.getServiceProvider());
  245. }
  246. // 主讲老师信息
  247. SysUser teacherInfo = sysUserFeignService.queryUserById(courseSchedule.getActualTeacherId());
  248. if (Objects.isNull(teacherInfo)) {
  249. throw new BizException("主讲老师不存在");
  250. }
  251. // RTC服务提供方
  252. roomResult.setServiceProvider(Optional.ofNullable(courseSchedule.getServiceProvider()).orElse("rongCloud"));
  253. //获取当前课程剩余时长
  254. roomResult.setSurplusTime(DateUtil.secondsBetween(new Date(), courseSchedule.getEndClassTime()));
  255. roomResult.setRoomId(roomId);
  256. // 网络课形式:RTC房间,直播间
  257. if (GroupType.LIVE == courseSchedule.getGroupType()) {
  258. if (Optional.ofNullable(joinRoom).orElse(true)) {
  259. String joinImGroupKey = "joinImGroup:" + roomId;
  260. // VIP课或网络课,IM群聊已创建标识
  261. redisTemplate.opsForValue().setIfAbsent(joinImGroupKey, roomId, 1L, TimeUnit.DAYS);
  262. }
  263. // 直播形式网络课
  264. ImLiveBroadcastRoom liveRoom;
  265. if (StringUtils.isNotBlank(courseSchedule.getLiveRoomId())) {
  266. // 直播间状态判断
  267. liveRoom = imLiveBroadcastRoomService.lambdaQuery()
  268. .eq(ImLiveBroadcastRoom::getRoomUid, courseSchedule.getLiveRoomId())
  269. .last("LIMIT 1")
  270. .one();
  271. if (Objects.isNull(liveRoom)) {
  272. // 创建网络课直播教室
  273. liveRoom = createVipGroupLiveRoom(roomId, courseSchedule);
  274. }
  275. // 直播间状态不在进行中
  276. if (liveRoom.getLiveState() != 1) {
  277. ImLiveBroadcastRoom updateInfo = new ImLiveBroadcastRoom();
  278. updateInfo.setId(liveRoom.getId());
  279. updateInfo.setVideoRecord("");
  280. updateInfo.setLiveStartTime(DateTime.now().toDate());
  281. // 更新直播间状态
  282. imLiveBroadcastRoomService.updateById(updateInfo);
  283. // 开启直播间
  284. imLiveBroadcastRoomService.createLiveRoom(liveRoom);
  285. }
  286. } else {
  287. // 创建网络课直播教室
  288. liveRoom = createVipGroupLiveRoom(roomId, courseSchedule);
  289. }
  290. // 返回直播间配置参数
  291. roomResult.setLiveRoomId(liveRoom.getRoomUid());
  292. // 主动触发用户加入直播间
  293. // imLiveBroadcastRoomService.joinRoom(liveRoom.getRoomUid(), sysUser.getId());
  294. } else {
  295. // 创建聊天群组
  296. if (Optional.ofNullable(joinRoom).orElse(true)) {
  297. // 创建IM群聊
  298. this.joinImGroup(roomId, courseSchedule.getActualTeacherId(), courseSchedule);
  299. }
  300. // RTC房间网络课
  301. genRtcRoomMemberInfoConfig(roomId, joinRoom, sysUser, userId, teacher, courseSchedule, curTime, roomResult, courseId);
  302. }
  303. log.info("join room: roomId = {}, userId = {}", roomId, userId);
  304. return new BaseResponse(roomResult);
  305. }
  306. /**
  307. * 创建网络课直播间
  308. * @param roomId 课程房间编号
  309. * @param courseSchedule 课程信息
  310. * @return ImLiveBroadcastRoom
  311. */
  312. private ImLiveBroadcastRoom createVipGroupLiveRoom(String roomId, CourseSchedule courseSchedule) {
  313. // 主动创建直播间
  314. VipGroup vipGroup = vipGroupDao.get(Long.parseLong(courseSchedule.getMusicGroupId()));
  315. if (Objects.isNull(vipGroup)) {
  316. throw new BizException("直播课程组不存在");
  317. }
  318. if (StringUtils.isBlank(vipGroup.getLiveConfigJson())) {
  319. throw new BizException("直播课程组未配置直播间");
  320. }
  321. ImLiveBroadcastRoom liveRoom = JSON.parseObject(vipGroup.getLiveConfigJson(), ImLiveBroadcastRoom.class);
  322. if (StringUtils.isBlank(liveRoom.getServiceProvider())) {
  323. //查询房间过期时间
  324. String liveClient = sysConfigDao.findConfigValue("live_client");
  325. liveRoom.setServiceProvider(liveClient);
  326. }
  327. String liveStartTime = MessageFormat.format("{0} {1}", DateUtil.format(courseSchedule.getClassDate(), DateUtil.DEFAULT_PATTERN),
  328. DateUtil.format(courseSchedule.getStartClassTime(), DateUtil.EXPANDED_TIME_FORMAT));
  329. DateTime time = DateTime.parse(liveStartTime, DateTimeFormat.forPattern(DateUtil.DEFAULT_PATTERN + " " + DateUtil.EXPANDED_TIME_FORMAT));
  330. String roomUid = "LIVE-" + roomId + "-" + time.toDate().getTime();
  331. liveRoom.setTenantId(TenantContextHolder.getTenantId());
  332. liveRoom.setRoomUid(roomUid);
  333. //liveRoom.setRoomConfig(liveRoom.getRoomConfig());
  334. liveRoom.setLiveState(1);
  335. liveRoom.setRoomState(0);
  336. liveRoom.setGroupType("LIVE");
  337. liveRoom.setCreatedBy(liveRoom.getSpeakerId());
  338. liveRoom.setCreatedTime(DateTime.now().toDate());
  339. liveRoom.setLiveStartTime(DateTime.now().toDate());
  340. liveRoom.setTenantId(courseSchedule.getTenantId());
  341. // 创建直播间
  342. imLiveBroadcastRoomService.save(liveRoom);
  343. // 开启直播间
  344. imLiveBroadcastRoomService.createLiveRoom(liveRoom);
  345. // 更新课程关联直播间
  346. CourseSchedule schedule = new CourseSchedule();
  347. schedule.setId(courseSchedule.getId());
  348. schedule.setTenantId(courseSchedule.getTenantId());
  349. schedule.setLiveRoomId(roomUid);
  350. courseScheduleDao.update(schedule);
  351. // 返回直播间信息
  352. return liveRoom;
  353. }
  354. /**
  355. * RTC房间成员信息配置
  356. * @param roomId 房间编号
  357. * @param joinRoom 是否加入房间
  358. * @param sysUser 用户信息
  359. * @param userId 用户编号
  360. * @param teacher 主讲老师信息
  361. * @param courseSchedule 课程信息
  362. * @param curTime 当前时间
  363. * @param roomResult 房间信息
  364. * @param courseId 课程编号
  365. * @throws Exception 异常信息
  366. */
  367. private void genRtcRoomMemberInfoConfig(String roomId,
  368. Boolean joinRoom,
  369. SysUser sysUser,
  370. String userId,
  371. Teacher teacher,
  372. CourseSchedule courseSchedule,
  373. Date curTime,
  374. RoomResult roomResult,
  375. Long courseId) throws Exception {
  376. // 全员静音状态
  377. Boolean muteAll = Optional.ofNullable(courseSchedule.getMuteAll()).orElse(false);
  378. RoomResult.MemberResult userResult = new RoomResult.MemberResult();
  379. RoomMember member = roomMemberDao.findByRidAndUid(roomId, userId);
  380. RoleEnum roleEnum;
  381. String userName;
  382. if (member == null) {
  383. int count = roomMemberDao.countByRidAndExcludeRole(roomId, RoleEnum.RoleAudience.getValue());
  384. if (count == roomProperties.getMaxCount()) {
  385. log.info("join error Over max count: roomId = {}, userId = {}", roomId, userId);
  386. throw new BizException(ErrorEnum.ERR_OVER_MAX_COUNT.getErrCode(), ErrorEnum.ERR_OVER_MAX_COUNT.getErrMsg());
  387. //return new BaseResponse(ErrorEnum.ERR_OVER_MAX_COUNT, ErrorEnum.ERR_OVER_MAX_COUNT.getErrMsg(), null);
  388. }
  389. boolean microphone = true;
  390. if (teacher != null && teacher.getId().equals(courseSchedule.getActualTeacherId())) {
  391. roleEnum = RoleTeacher;
  392. userName = sysUser.getRealName();
  393. } else {
  394. roleEnum = RoleStudent;
  395. userName = sysUser.getUsername();
  396. // 学生加入房间,判定老师是否已开启全员静音
  397. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(courseSchedule.getServiceProvider())) {
  398. microphone = !muteAll;
  399. }
  400. }
  401. userResult.setMicrophone(microphone);
  402. userResult.setCamera(true);
  403. userResult.setHandUpOn(false);
  404. userResult.setJoinTime(curTime);
  405. if (Optional.ofNullable(joinRoom).orElse(true)) {
  406. saveRoomMember(userId, sysUser.getAvatar(), userName, roomId, roleEnum.getValue(), curTime, microphone);
  407. }
  408. } else {
  409. roleEnum = RoleEnum.getEnumByValue(member.getRole());
  410. if (roleEnum == RoleTeacher && Optional.ofNullable(joinRoom).orElse(true)) {
  411. courseScheduleStudentPaymentDao.adjustPlayMidi(courseId, null, null);
  412. }
  413. userName = member.getName();
  414. //userResult.setRole(member.getRole());
  415. userResult.setMicrophone(member.isMic());
  416. userResult.setCamera(member.isCamera());
  417. userResult.setHandUpOn(member.isHand());
  418. userResult.setJoinTime(member.getJoinDt());
  419. }
  420. // imHelper.joinGroup(new String[]{userId}, roomId, roomId);
  421. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(courseSchedule.getServiceProvider());
  422. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  423. // 腾讯云RTC
  424. // 用户IM帐号创建
  425. String userSig = "";
  426. try {
  427. userSig = pluginService.register(String.valueOf(sysUser.getId()), sysUser.getRealName(), sysUser.getAvatar());
  428. } catch (Exception e) {
  429. log.error("直播房间用户注册失败: userId={}", sysUser.getId(), e);
  430. }
  431. // 返回配置参数
  432. roomResult.userSig(userSig)
  433. .rtcRoomConfig(rtcRoomPluginContext.getPluginService().getRTCRoomConfig(String.valueOf(sysUser.getId())))
  434. .setGroupId(roomId);
  435. }
  436. List<CourseScheduleStudentMusicScore> scheduleStudentMusicScores = courseScheduleStudentMusicScoreDao.queryByScoreIdAndCourseId(null, courseId, null, null, null);
  437. Room room = roomDao.findByRid(roomId);
  438. String display = "";
  439. if (roleEnum == RoleTeacher || roleEnum == RoleEnum.RoleAssistant) {
  440. display = "display://type=" + roleEnum.ordinal() + "?userId=" + userId + "?uri=";
  441. // 发送显示主屏消息
  442. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomResult.getServiceProvider())) {
  443. // 网络教室人员信息
  444. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  445. // 发送消息
  446. sendDisplayMessage(display, roomMember);
  447. }
  448. } else {
  449. ExamSongDownloadData examSongDownloadData;
  450. String json = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(courseId, sysUser.getId());
  451. if (StringUtils.isEmpty(json)) {
  452. examSongDownloadData = new ExamSongDownloadData();
  453. } else {
  454. examSongDownloadData = JSON.parseObject(json, ExamSongDownloadData.class);
  455. }
  456. //获取学员曲目下载状态
  457. userResult.setExamSongDownloadJson(examSongDownloadData);
  458. if (room != null) {
  459. display = room.getDisplay();
  460. }
  461. }
  462. //已下载的伴奏列表
  463. if (scheduleStudentMusicScores != null && scheduleStudentMusicScores.size() > 0) {
  464. List<CourseScheduleStudentMusicScore> musicScores = scheduleStudentMusicScores.stream().filter(e -> e.getUserId().equals(sysUser.getId())).collect(Collectors.toList());
  465. String toJSONString = JSON.toJSONString(musicScores, SerializerFeature.DisableCircularReferenceDetect);
  466. List<CourseScheduleStudentMusicScore> lists = JSON.parseArray(toJSONString, CourseScheduleStudentMusicScore.class);
  467. userResult.setScheduleStudentMusicScores(lists);
  468. }
  469. userResult.setUserName(userName);
  470. userResult.setUserId(userId);
  471. userResult.setRole(roleEnum.getValue());
  472. //获取节拍器信息
  473. String midi = courseScheduleStudentPaymentDao.getMidiByCourseIdAndUserId(courseId.toString(), userId);
  474. userResult.setPlayMidiJson(JSONObject.parseObject(midi, CustomMessage.class));
  475. roomResult.setUserInfo(userResult);
  476. roomResult.setDisplay(display);
  477. // 课程人数
  478. {
  479. // 当前教室人数
  480. int studentNums = courseScheduleStudentPaymentDao.findByCourseSchedule(Long.parseLong(roomId.substring(1))).size();
  481. // 网管课
  482. /*if (courseSchedule.getGroupType() == GroupType.VIP) {
  483. studentNums = vipGroupDao.getCourseStudentNumsByGroupId(Long.parseLong(courseSchedule.getMusicGroupId()));
  484. }*/
  485. roomResult.setStudentNums(studentNums);
  486. }
  487. List<RoomMember> roomMemberList = roomMemberDao.findByRid(roomId);
  488. if (CollectionUtils.isNotEmpty(roomMemberList)) {
  489. // 获取当前房间所有用户去重
  490. Collection<RoomMember> roomMembers = roomMemberList.stream()
  491. .collect(Collectors.toMap(RoomMember::getUid, Function.identity(), (o, n) -> n)).values();
  492. // 重置房间用户信息
  493. roomMemberList = Lists.newArrayList(roomMembers);
  494. Set<String> userIds = roomMemberList.stream().map(RoomMember::getUid).collect(Collectors.toSet());
  495. Map<Integer, String> midiMap = MapUtil.convertMybatisMap(courseScheduleStudentPaymentDao.queryMidiByUserIdsAndCourseId(userIds, courseId.toString()));
  496. Map<Integer, String> examSongMap = MapUtil.convertMybatisMap(courseScheduleStudentPaymentDao.queryExamSongByUserIdsAndCourseId(userIds, courseId.toString()));
  497. roomResult.setMembers(roomMemberList, midiMap, examSongMap, scheduleStudentMusicScores);
  498. // 全员静音状态开启
  499. if (muteAll && TencentCloudRTCPlugin.PLUGIN_NAME.equals(courseSchedule.getServiceProvider())) {
  500. for (RoomResult.MemberResult item : roomResult.getMembers()) {
  501. // 重置学生用户当前静音状态
  502. if (RoleStudent.getValue() == item.getRole()) {
  503. item.setMicrophone(false);
  504. }
  505. }
  506. }
  507. }
  508. roomResult.setWhiteboards(whiteboardDao.findByRid(roomId));
  509. if (room != null) {
  510. roomResult.setSoundVolume(room.getSoundVolume());
  511. }
  512. //是否使用自定义白板
  513. String rongyun_here_white_flag = sysConfigDao.findConfigValue("rongyun_here_white_flag");
  514. if(StringUtils.isNotEmpty(rongyun_here_white_flag)){
  515. HashMap<Integer,Integer> hashMap = JSONObject.parseObject(rongyun_here_white_flag, HashMap.class);
  516. Integer s = hashMap.get(courseSchedule.getOrganId());
  517. if(s == null){
  518. roomResult.setRandomNumeric("0");
  519. }else {
  520. roomResult.setRandomNumeric(s.toString());
  521. }
  522. }else {
  523. roomResult.setRandomNumeric("1");
  524. }
  525. log.info("join room: roomId = {}, userId = {}, userName={}, role = {}", roomId, userId, userName, roleEnum);
  526. }
  527. private void joinImGroup(String roomId, Integer actualTeacherId, CourseSchedule courseSchedule) throws Exception {
  528. String joinImGroupKey = "joinImGroup:" + roomId;
  529. // VIP课或网络课,IM群聊已创建标识
  530. Boolean exists = redisTemplate.opsForValue().setIfAbsent(joinImGroupKey, roomId, 1L, TimeUnit.DAYS);
  531. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(courseSchedule.getServiceProvider());
  532. if (Optional.ofNullable(exists).orElse(false)) {
  533. try {
  534. // 创建群组
  535. log.info("createImGroup: roomId = {}, userId = {}", roomId, actualTeacherId);
  536. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  537. // 群组帐号注册
  538. Teacher teacher = teacherDao.get(courseSchedule.getTeacherId());
  539. if (Objects.nonNull(teacher)) {
  540. try {
  541. pluginService.register(courseSchedule.getTeacherId().toString(), teacher.getRealName(), teacher.getAvatar());
  542. } catch (Exception e) {
  543. log.error("直播房间群主注册失败: userId={}", courseSchedule.getTeacherId(), e);
  544. }
  545. }
  546. // 生成群组
  547. pluginService.chatRoomCreate(roomId, courseSchedule.getName(), courseSchedule.getTeacherId().toString());
  548. // 群组老师信息
  549. List<ImGroupMemberWrapper.ImGroupMember> groupMembers = Lists.newArrayList(ImGroupMemberWrapper.ImGroupMember
  550. .builder()
  551. .userId(Long.valueOf(actualTeacherId))
  552. .imUserIdFormat(false)
  553. .build());
  554. List<CourseScheduleStudentPayment> payments = courseScheduleStudentPaymentDao.findByCourseSchedule(Long.parseLong(roomId.substring(1)));
  555. // 群组学生信息
  556. if (CollectionUtils.isNotEmpty(payments)) {
  557. for (CourseScheduleStudentPayment item : payments) {
  558. groupMembers.add(ImGroupMemberWrapper.ImGroupMember
  559. .builder()
  560. .userId(Long.valueOf(item.getUserId()))
  561. .imUserIdFormat(false)
  562. .build());
  563. }
  564. }
  565. // 加入群组成员
  566. log.info("joinImGroup: roomId = {}, serviceProvider={}, userIds = {}", roomId, courseSchedule.getServiceProvider(), groupMembers);
  567. pluginService.chatRoomGroupJoin(roomId, courseSchedule.getName(), groupMembers);
  568. } else {
  569. List<CourseScheduleStudentPayment> payments = courseScheduleStudentPaymentDao.findByCourseSchedule(Long.parseLong(roomId.substring(1)));
  570. List<String> collect = payments.stream().map(e -> e.getUserId().toString()).collect(Collectors.toList());
  571. collect.add(actualTeacherId.toString());
  572. String[] integers = collect.toArray(new String[]{});
  573. imHelper.joinGroup(integers, roomId, roomId);
  574. }
  575. } catch (Exception e) {
  576. redisTemplate.delete(joinImGroupKey);
  577. // 异常抛出,删除缓存标识
  578. throw e;
  579. }
  580. }
  581. }
  582. private void dismissImGroup(String userId,String roomId, String serviceProvider) throws Exception {
  583. log.info("dismissImGroup: roomId = {}, userId = {}", roomId, userId);
  584. String joinImGroupKey = "joinImGroup:" + roomId;
  585. redisTemplate.delete(joinImGroupKey);
  586. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(serviceProvider);
  587. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  588. // 腾讯云群销毁
  589. pluginService.chatRoomDestroy(roomId);
  590. } else {
  591. // 融云群销毁
  592. // 销毁群组
  593. imHelper.dismiss(userId, roomId);
  594. }
  595. }
  596. public RoomMember saveRoomMember(String roomId, String userId) {
  597. SysUser sysUser = sysUserFeignService.queryUserById(Integer.parseInt(userId));
  598. Teacher teacher = teacherDao.get(Integer.parseInt(userId));
  599. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(roomId.substring(1)));
  600. Date curTime = DateTimeUtils.currentUTC();
  601. RoleEnum roleEnum;
  602. RoomMember member = roomMemberDao.findByRidAndUid(roomId, userId);
  603. String userName;
  604. if (member == null) {
  605. boolean microphone = true;
  606. if (teacher != null && teacher.getId().equals(courseSchedule.getActualTeacherId())) {
  607. roleEnum = RoleTeacher;
  608. userName = sysUser.getRealName();
  609. } else {
  610. roleEnum = RoleStudent;
  611. userName = sysUser.getUsername();
  612. // 判定老师是否已开启全员静音
  613. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(courseSchedule.getServiceProvider())) {
  614. microphone = !courseSchedule.getMuteAll();
  615. }
  616. }
  617. member = saveRoomMember(userId, sysUser.getAvatar(), userName, roomId, roleEnum.getValue(), curTime, microphone);
  618. }
  619. return member;
  620. }
  621. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  622. @Override
  623. public void joinRoomFailure(String roomId, String userId) {
  624. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  625. if (roomMember == null) {
  626. return;
  627. }
  628. log.info("joinRoomFailure : roomId={}, userId={}", roomId, userId);
  629. //如果加入失败,删除该用户数据
  630. roomMemberDao.deleteUserByRidAndUid(roomId, userId);
  631. }
  632. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  633. @Override
  634. public void joinRoomSuccess(String roomId, String userId, String deviceNum) throws Exception {
  635. log.info("joinRoomSuccess: roomId={}, userId={}, deviceNum={}", roomId, userId, deviceNum);
  636. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  637. if (roomMember == null) {
  638. roomMember = saveRoomMember(roomId, userId);
  639. }
  640. String joinSuccessKey = "joinRoomSuccess" + roomId + userId;
  641. Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(joinSuccessKey, roomId, 1l, TimeUnit.SECONDS);
  642. if (!aBoolean) {
  643. RoleEnum roleEnum = RoleEnum.getEnumByValue(roomMember.getRole());
  644. if (roleEnum == RoleTeacher && StringUtils.isNotEmpty(deviceNum)) {
  645. teacherAttendanceService.updateDeviceNum(Integer.parseInt(roomId.substring(1)), userId, deviceNum, null);
  646. // signInSuccess(roomMember,deviceNum);
  647. }
  648. return;
  649. }
  650. RoleEnum roleEnum = RoleEnum.getEnumByValue(roomMember.getRole());
  651. CourseSchedule schedule = courseScheduleDao.getLock(Long.parseLong(roomId.substring(1)));
  652. String display = "";
  653. if (roleEnum == RoleTeacher) {
  654. //如果是老师加入房间,调整节拍器状态
  655. courseScheduleStudentPaymentDao.adjustPlayMidi(schedule.getId(), null, null);
  656. display = "display://type=1?userId=" + userId + "?uri=";
  657. } else if (roleEnum == RoleEnum.RoleAssistant) {
  658. display = "display://type=0?userId=" + userId + "?uri=";
  659. }
  660. Date curTime = DateTimeUtils.currentUTC();
  661. Room room = roomDao.findByRid(roomId);
  662. log.info("joinRoomSuccess: roomId={}, userId={}, roleEnum={}, room={}", roomId, userId, roleEnum.name(), Objects.isNull(room));
  663. if (room == null) {
  664. saveRoom(roomId, roomId, curTime, display);
  665. this.joinImGroup(roomId, schedule.getActualTeacherId(), schedule);
  666. } else {
  667. if (roleEnum == RoleTeacher || roleEnum == RoleEnum.RoleAssistant) {
  668. updateDisplay(roomId, userId, display, 0);
  669. }
  670. }
  671. UserInfo userInfo = userDao.findByUid(userId);
  672. if (userInfo == null) {
  673. userInfo = new UserInfo();
  674. userInfo.setUid(userId);
  675. userInfo.setName(roomMember.getName());
  676. userInfo.setCreateDt(curTime);
  677. userInfo.setUpdateDt(curTime);
  678. userDao.save(userInfo);
  679. }
  680. MemberChangedMessage msg = new MemberChangedMessage(MemberChangedMessage.Action_Join, userId, roleEnum.getValue());
  681. msg.setTimestamp(curTime);
  682. msg.setUserName(roomMember.getName());
  683. msg.setCamera(true);
  684. Boolean playMidi = false;
  685. Boolean examSong = false;
  686. if (roleEnum == RoleStudent) {
  687. String midiByCourseIdAndUserId = courseScheduleStudentPaymentDao.getMidiByCourseIdAndUserId(schedule.getId().toString(), userId);
  688. //获取节拍器信息
  689. if (StringUtils.isNotEmpty(midiByCourseIdAndUserId)) {
  690. JSONObject jsonObject = JSONObject.parseObject(midiByCourseIdAndUserId);
  691. if (jsonObject.get("enable") != null) {
  692. playMidi = Boolean.parseBoolean(jsonObject.get("enable").toString());
  693. }
  694. }
  695. String examJson = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(schedule.getId(), Integer.parseInt(userId));
  696. if (StringUtils.isNotEmpty(examJson)) {
  697. ExamSongDownloadData examSongDownloadData = JSON.parseObject(examJson, ExamSongDownloadData.class);
  698. examSong = examSongDownloadData.getEnable();
  699. }
  700. }
  701. msg.setHandUpOn(roomMember.isHand());
  702. msg.setMetronomeSwitch(playMidi);
  703. msg.setExamSongSwitch(examSong);
  704. // 获取RTC服务提供方
  705. String rtcServiceProvider = Optional.ofNullable(schedule.getServiceProvider()).orElse("rongCloud");
  706. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(rtcServiceProvider);
  707. if (rtcServiceProvider.equals(TencentCloudRTCPlugin.PLUGIN_NAME)) {
  708. // 腾讯云RTC服务
  709. RTCRoomMessage.MessageContent.MessageContentBuilder action = RTCRoomMessage.MessageContent.builder()
  710. .action(EMemberAction.JOIN.getValue());
  711. if (roleEnum == RoleTeacher) {
  712. action.role(roleEnum.getValue());
  713. } else {
  714. action.role(roleEnum.getValue());
  715. }
  716. action.handUpOn(roomMember.isHand())
  717. .microphone(roomMember.isMic())
  718. .timestamp(curTime.getTime())
  719. .camera(true)
  720. .sendUserInfo(getSendUser(userId,roleEnum));
  721. // 开启全员静音,重置学员状态
  722. if (schedule.getMuteAll()) {
  723. action.microphone(false);
  724. }
  725. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  726. .objectName(RTCRoomMessage.MEMBER_CHANGE_MESSAGE)
  727. .fromUserId(userId)
  728. .content(action.build())
  729. .toChatRoomId(roomId)
  730. .isPersisted(1)
  731. .isIncludeSender(1)
  732. .build();
  733. pluginService.sendChatRoomMessage(roomMessage);
  734. } else {
  735. imHelper.publishMessage(userId, roomId, msg);
  736. }
  737. log.info("join room success: roomId = {}, userId = {}, role = {}", roomId, userId, roleEnum);
  738. signInSuccess(roomMember, deviceNum);
  739. }
  740. public void signInSuccess(RoomMember roomMember, String deviceNum) {
  741. String roomId = roomMember.getRid();
  742. String userId = roomMember.getUid();
  743. String currentRoomIdKey = roomId + userId;
  744. Long firstCourseId = Long.parseLong(roomId.substring(1));
  745. Long currentRoomId;
  746. if (redisTemplate.hasKey(currentRoomIdKey)) {
  747. currentRoomId = Long.parseLong(redisTemplate.opsForValue().get(currentRoomIdKey));
  748. } else {
  749. log.error("signInFailure: roomId={}, userId={}", roomId, userId);
  750. currentRoomId = firstCourseId;
  751. }
  752. log.info("signInSuccess: roomId={}, userId={},currentRoomId={}", roomId, userId, currentRoomId);
  753. Integer userIdInt = Integer.parseInt(userId);
  754. RoleEnum roleEnum = RoleEnum.getEnumByValue(roomMember.getRole());
  755. if (roleEnum == RoleTeacher) {
  756. teacherAttendanceService.addTeacherAttendanceSignIn(firstCourseId, userIdInt, currentRoomId, deviceNum);
  757. } else {
  758. studentAttendanceService.addStudentAttendanceSignIn(firstCourseId, userIdInt, currentRoomId);
  759. }
  760. redisTemplate.delete(roomId + userId);
  761. }
  762. public void saveRoom(String roomId, String roomName, Date createTime, String display) {
  763. Room room = new Room();
  764. room.setRid(roomId);
  765. room.setName(roomName);
  766. room.setCreateDt(createTime);
  767. room.setDisplay(display);
  768. room.setWhiteboardNameIndex(0);
  769. roomDao.save(room);
  770. }
  771. public RoomMember saveRoomMember(String userId, String headUrl, String userName, String roomId, int role, Date joinTime, Boolean muteAll) {
  772. RoomMember roomMember = new RoomMember();
  773. roomMember.setUid(userId);
  774. roomMember.setName(userName);
  775. roomMember.setRid(roomId);
  776. roomMember.setRole(role);
  777. roomMember.setCamera(true);
  778. roomMember.setJoinDt(joinTime);
  779. roomMember.setMusicMode(false);
  780. roomMember.setHeadUrl(headUrl);
  781. roomMember.setMic(muteAll);
  782. roomMemberDao.save(roomMember);
  783. return roomMember;
  784. }
  785. public String getRoomServiceProvider(String roomId ) {
  786. Integer firstCourseId = Integer.parseInt(roomId.substring(1));
  787. CourseSchedule courseSchedule = courseScheduleDao.get(firstCourseId.longValue());
  788. return courseSchedule.getServiceProvider();
  789. }
  790. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
  791. @Override
  792. public void leaveRoomSuccess(String roomId, String userId, String deviceNum) throws Exception {
  793. // 用户退出房间多次触发调用判定
  794. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  795. if (Objects.isNull(roomMember)) {
  796. log.warn("leaveRoomSuccess: REPEATED_EXECUTION roomId={}, userId={}, deviceNum={}", roomId, userId, deviceNum);
  797. return;
  798. }
  799. log.info("leaveRoomSuccess: roomId={}, userId={}, deviceNum={}", roomId, userId, deviceNum);
  800. Integer firstCourseId = Integer.parseInt(roomId.substring(1));
  801. RoleEnum roleEnum;
  802. int parseInt = Integer.parseInt(userId);
  803. Teacher teacher = teacherDao.get(parseInt);
  804. CourseSchedule courseSchedule = courseScheduleDao.get(firstCourseId.longValue());
  805. if (teacher != null && teacher.getId().equals(courseSchedule.getActualTeacherId())) {
  806. roleEnum = RoleTeacher;
  807. courseScheduleStudentMusicScoreDao.closePlayStatus(courseSchedule.getId(), null, null);
  808. } else {
  809. roleEnum = RoleStudent;
  810. }
  811. String leaveSuccessKey = "leaveRoomSuccess" + roomId + userId;
  812. Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(leaveSuccessKey, roomId, 1L, TimeUnit.SECONDS);
  813. log.info("leaveRoomSuccess: roomId={}, userId={},deviceNum={},aBoolean={}", roomId, userId, deviceNum, aBoolean);
  814. if (Boolean.FALSE.equals(aBoolean)) {
  815. if (StringUtils.isNotEmpty(deviceNum)) {
  816. //如果设备号不为空,更新设备号
  817. if (roleEnum == RoleTeacher) {
  818. teacherAttendanceService.updateDeviceNum(firstCourseId, userId, null, deviceNum);
  819. // teacherAttendanceService.addTeacherAttendanceSignOut(firstCourseId.longValue(),parseInt,deviceNum);
  820. }
  821. }
  822. return;
  823. }
  824. String username;
  825. SysUser sysUser = sysUserFeignService.queryUserById(parseInt);
  826. if (roleEnum == RoleTeacher) {
  827. username = sysUser.getRealName();
  828. courseScheduleStudentPaymentDao.adjustPlayMidi(firstCourseId, null, null);
  829. courseScheduleStudentPaymentDao.adjustExamSong(firstCourseId.longValue(), null, null);
  830. teacherAttendanceService.addTeacherAttendanceSignOut(firstCourseId.longValue(), parseInt, deviceNum);
  831. //关闭所有曲目播放
  832. courseScheduleStudentMusicScoreDao.closePlayStatus(firstCourseId, null, null);
  833. } else {
  834. username = sysUser.getUsername();
  835. studentAttendanceService.addStudentAttendanceSignOut(firstCourseId.longValue(), parseInt);
  836. }
  837. Room room = roomDao.findByRid(roomId);
  838. if (room == null) {
  839. roomMemberDao.deleteUserByRidAndUid(roomId, userId);
  840. userDao.deleteByUid(userId);
  841. return;
  842. }
  843. if (roleEnum != RoleStudent && isUserDisplay(room, userId)) {
  844. updateDisplay(roomId, userId, "", 0);
  845. }
  846. if (roomMemberDao.countByRid(roomId) <= 1) {
  847. // 删除群组用户信息
  848. roomMemberDao.deleteUserByRidAndUid(roomId, userId);
  849. // 删除群组信息
  850. roomDao.deleteByRid(roomId);
  851. if (GroupType.LIVE != courseSchedule.getGroupType()) {
  852. // 删除白板信息
  853. deleteWhiteboardByUser(roomId, userId);
  854. // 删除群组
  855. this.dismissImGroup(userId, roomId, courseSchedule.getServiceProvider());
  856. //关闭所有曲目播放
  857. courseScheduleStudentMusicScoreDao.closePlayStatus(courseSchedule.getId(), null, null);
  858. }
  859. log.info("leaveRoomSuccess dismiss the room: {}, userId: {}, role={}", roomId, userId, roleEnum.name());
  860. } else {
  861. roomMemberDao.deleteUserByRidAndUid(roomId, userId);
  862. if (GroupType.LIVE != courseSchedule.getGroupType()) {
  863. // 获取RTC服务提供方
  864. String rtcServiceProvider = Optional.ofNullable(courseSchedule.getServiceProvider()).orElse("rongCloud");
  865. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(rtcServiceProvider);
  866. if (rtcServiceProvider.equals(TencentCloudRTCPlugin.PLUGIN_NAME)) {
  867. // 腾讯云RTC服务
  868. RTCRoomMessage.MessageContent messageContent = RTCRoomMessage.MessageContent
  869. .builder()
  870. .action(EMemberAction.LEAVE.getValue())
  871. .role(roleEnum.getValue())
  872. .handUpOn(false)
  873. .timestamp(System.currentTimeMillis())
  874. .microphone(false)
  875. .camera(false)
  876. .sendUserInfo(getSendUser(userId, roleEnum))
  877. .build();
  878. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  879. .objectName(RTCRoomMessage.MEMBER_CHANGE_MESSAGE)
  880. .toChatRoomId(roomId)
  881. .content(messageContent)
  882. .fromUserId(userId)
  883. .isPersisted(1)
  884. .isIncludeSender(1)
  885. .build();
  886. pluginService.sendChatRoomMessage(roomMessage);
  887. } else {
  888. MemberChangedMessage msg = new MemberChangedMessage(MemberChangedMessage.Action_Leave, userId, roleEnum.getValue());
  889. msg.setUserName(username);
  890. imHelper.publishMessage(userId, roomId, msg);
  891. // imHelper.quit(new String[]{userId}, roomId);
  892. }
  893. }
  894. log.info("leaveRoomSuccess quit group: roomId={},userId: {}", roomId, userId);
  895. }
  896. userDao.deleteByUid(userId);
  897. }
  898. /**
  899. * 事件回调通知
  900. *
  901. * @param roomId 房间编号
  902. * @param userId 用户编号
  903. * @param deviceNum 设备编号
  904. * @param callbackTs 事件回调时间
  905. * @throws Exception Exception
  906. */
  907. @Transactional
  908. @Override
  909. public void leaveRoomSuccess(String roomId, String userId, String deviceNum, Long callbackTs) throws Exception {
  910. // 用户退出房间多次触发调用判定
  911. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  912. if (Objects.isNull(roomMember)) {
  913. log.warn("leaveRoomSuccess: REPEATED_EXECUTION roomId={}, userId={}, deviceNum={}", roomId, userId, deviceNum);
  914. return;
  915. }
  916. // 回调整事件延迟通知
  917. if (callbackTs < roomMember.getJoinDt().getTime()) {
  918. log.warn("leaveRoomSuccess: q roomId={}, userId={}, deviceNum={}, callbackTs={}, joinTs={}",
  919. roomId, userId, deviceNum, callbackTs, roomMember.getJoinDt().getTime());
  920. return;
  921. }
  922. log.info("leaveRoomSuccess: roomId={}, userId={}, deviceNum={}, joinTs={}, callbackTs={}", roomId, userId, deviceNum,
  923. roomMember.getJoinDt().getTime(), callbackTs);
  924. // 用户离开事件
  925. leaveRoomSuccess(roomId, userId, deviceNum);
  926. }
  927. public void deleteWhiteboardByUser(String roomId, String userId) throws Exception {
  928. List<Whiteboard> whiteboardList = whiteboardDao.findByRidAndCreator(roomId, userId);
  929. if (!whiteboardList.isEmpty()) {
  930. whiteboardDao.deleteByRidAndCreator(roomId, userId);
  931. for (Whiteboard wb : whiteboardList) {
  932. whiteBoardHelper.destroy(wb.getWbRoom());
  933. }
  934. }
  935. }
  936. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  937. @Override
  938. public void destroyRoom(String roomId) {
  939. // 查询课程信息
  940. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(roomId.substring(1)));
  941. if (Objects.isNull(courseSchedule)) {
  942. throw new BizException("无效的课程编号");
  943. }
  944. whiteboardDao.deleteByRid(roomId);
  945. Room room = roomDao.findByRid(roomId);
  946. if (room == null) {
  947. List<RoomMember> list = roomMemberDao.findByRid(roomId);
  948. if (!list.isEmpty()) {
  949. try {
  950. this.dismissImGroup(list.get(0).getUid(), roomId, courseSchedule.getServiceProvider());
  951. } catch (Exception e) {
  952. log.error("destroyRoom: {}", e.getMessage());
  953. e.printStackTrace();
  954. }
  955. }
  956. roomMemberDao.deleteByRid(roomId);
  957. log.info("destroyRoom: {}", roomId);
  958. }
  959. }
  960. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  961. @Override
  962. public Boolean downgrade(String roomId, List<ReqChangeUserRoleData.ChangedUser> users) throws Exception {
  963. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  964. CheckUtils.checkArgument(users.size() > 0, "the changed user list must't be null");
  965. SysUser authUser = sysUserFeignService.queryUserInfo();
  966. String userId = authUser.getId().toString();
  967. Room room = roomDao.findByRid(roomId);
  968. if (room == null) {
  969. throw new ApiException(ErrorEnum.ERR_ROOM_NOT_EXIST);
  970. }
  971. boolean result = false;
  972. List<RoleChangedMessage.ChangedUser> changedUsers = new ArrayList<>();
  973. for (ReqChangeUserRoleData.ChangedUser user : users) {
  974. String changedUserId = user.getUserId();
  975. RoleEnum changedRole = RoleEnum.getEnumByValue(user.getRole());
  976. if (changedUserId.equals(userId)) {
  977. log.error("can not change self role: {}, {}, {}", roomId, userId, changedRole);
  978. throw new ApiException(ErrorEnum.ERR_CHANGE_SELF_ROLE);
  979. } else {
  980. RoomMember oldUser = roomMemberDao.findByRidAndUid(roomId, changedUserId);
  981. if (oldUser != null) {
  982. if (changedRole.equals(RoleEnum.RoleAudience)) {
  983. int r = roomMemberDao.updateRoleByRidAndUid(roomId, changedUserId, changedRole.getValue());
  984. RoleChangedMessage.ChangedUser u = new RoleChangedMessage.ChangedUser(changedUserId, changedRole.getValue());
  985. UserInfo userInfo = userDao.findByUid(changedUserId);
  986. if (userInfo != null) {
  987. u.setUserName(userInfo.getName());
  988. }
  989. changedUsers.add(u);
  990. log.info("change the role: {}, {}, {}, result: {}", roomId, userId, changedRole, r);
  991. result = true;
  992. }
  993. if (oldUser.getRole() == RoleTeacher.getValue() && isUserDisplay(room, oldUser.getUid())) {
  994. updateDisplay(roomId, userId, "", 1);
  995. } else {
  996. log.info("don't update display: room={}, userRole={}", room, RoleEnum.getEnumByValue(oldUser.getRole()));
  997. }
  998. } else {
  999. log.info("role changed fail, not exist: {} - {} - {}", roomId, userId, changedRole);
  1000. }
  1001. }
  1002. }
  1003. if (result) {
  1004. RoleChangedMessage msg = new RoleChangedMessage(userId);
  1005. msg.setUsers(changedUsers);
  1006. imHelper.publishMessage(userId, roomId, msg, 1);
  1007. }
  1008. return result;
  1009. }
  1010. @Override
  1011. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  1012. public Boolean kickMember(String roomId) throws Exception {
  1013. SysUser authUser = sysUserFeignService.queryUserInfo();
  1014. String userId = authUser.getId().toString();
  1015. CheckUtils.checkArgument(userId != null, "userId must't be null");
  1016. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1017. log.info("kickMember: roomId={}, userId={}", roomId, userId);
  1018. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1019. if (roomMember == null) {
  1020. return true;
  1021. }
  1022. Room room = roomDao.findByRid(roomId);
  1023. Integer firstCourseId = Integer.parseInt(roomId.substring(1));
  1024. CourseSchedule courseSchedule = courseScheduleDao.get(firstCourseId.longValue());
  1025. MemberChangedMessage msg = new MemberChangedMessage(MemberChangedMessage.Action_Kick, userId, roomMember.getRole());
  1026. msg.setUserName(roomMember.getName());
  1027. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(courseSchedule.getServiceProvider())) {
  1028. sendJoinLeaveMessage(roomMember, MemberChangedMessage.Action_Kick);
  1029. } else {
  1030. imHelper.publishMessage(userId, roomId, msg, 1);
  1031. }
  1032. if (roomMember.getRole() == RoleTeacher.getValue() && isUserDisplay(room, userId)) {
  1033. updateDisplay(roomId, userId, "", 1);
  1034. }
  1035. roomMemberDao.deleteUserByRidAndUid(roomId, userId);
  1036. userDao.deleteByUid(userId);
  1037. // IMApiResultInfo apiResultInfo = imHelper.quit(new String[]{userId}, roomId);
  1038. // if (!apiResultInfo.isSuccess()) {
  1039. // throw new ApiException(ErrorEnum.ERR_EXIT_ROOM_ERROR, apiResultInfo.getErrorMessage());
  1040. // }
  1041. return true;
  1042. }
  1043. private void sendJoinLeaveMessage(RoomMember roomMember, int status) throws Exception {
  1044. // 获取RTC服务提供方
  1045. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(TencentCloudRTCPlugin.PLUGIN_NAME);
  1046. // 腾讯云RTC服务
  1047. RTCRoomMessage.MessageContent.MessageContentBuilder action = RTCRoomMessage.MessageContent.builder()
  1048. .action(status)
  1049. .timestamp(System.currentTimeMillis())
  1050. .role(roomMember.getRole());
  1051. action.handUpOn(false)
  1052. .microphone(false)
  1053. .camera(false).sendUserInfo(getSendUser(roomMember.getUid(),RoleEnum.getEnumByValue(roomMember.getRole())));
  1054. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  1055. .objectName(RTCRoomMessage.MEMBER_CHANGE_MESSAGE)
  1056. .content(action.build())
  1057. .toChatRoomId(roomMember.getRid())
  1058. .fromUserId(roomMember.getUid())
  1059. .isIncludeSender(1)
  1060. .isPersisted(1)
  1061. .build();
  1062. pluginService.sendChatRoomMessage(roomMessage);
  1063. }
  1064. @Override
  1065. @Transactional(rollbackFor = Exception.class)
  1066. public Boolean display(String roomId, int type, String uri, String targetUserId) throws Exception {
  1067. // 重置uri为空字符串
  1068. if (StringUtils.isBlank(uri) || "null".equals(uri)) {
  1069. uri = "";
  1070. }
  1071. SysUser authUser = sysUserFeignService.queryUserInfo();
  1072. String userId = authUser.getId().toString();
  1073. log.info("display in room: {}, type = {}, uri = {}", roomId, type, uri);
  1074. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1075. CheckUtils.checkArgument(type >= 0 && type < DisplayEnum.values().length, "type not exist");
  1076. DisplayEnum displayEnum = DisplayEnum.values()[type];
  1077. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1078. String roomServiceProviter = getRoomServiceProvider(roomId);
  1079. if (displayEnum.equals(DisplayEnum.None)) {
  1080. roomDao.updateDisplayByRid(roomId, "");
  1081. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1082. sendDisplayMessage("", roomMember);
  1083. } else {
  1084. DisplayMessage displayMessage = new DisplayMessage("");
  1085. IMApiResultInfo apiResultInfo = imHelper.publishMessage(userId, roomId, displayMessage);
  1086. if (apiResultInfo.isSuccess()) {
  1087. return true;
  1088. } else {
  1089. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, apiResultInfo.getErrorMessage());
  1090. }
  1091. }
  1092. }
  1093. String display = "display://type=" + type;
  1094. if (displayEnum.equals(DisplayEnum.Teacher)) {
  1095. List<RoomMember> teachers = roomMemberDao.findByRidAndRole(roomId, RoleTeacher.getValue());
  1096. if (teachers.isEmpty()) {
  1097. throw new ApiException(ErrorEnum.ERR_TEACHER_NOT_EXIST_IN_ROOM);
  1098. } else {
  1099. display += "?userId=" + teachers.get(0).getUid() + "?uri=";
  1100. roomDao.updateDisplayByRid(roomId, display);
  1101. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1102. sendDisplayMessage(display, roomMember);
  1103. } else {
  1104. DisplayMessage displayMessage = new DisplayMessage(display);
  1105. imHelper.publishMessage(userId, roomId, displayMessage);
  1106. }
  1107. log.info("change display to teacher: roomId={}, display={}", roomId, display);
  1108. }
  1109. } else if (displayEnum.equals(DisplayEnum.Assistant)) {
  1110. List<RoomMember> assistants = roomMemberDao.findByRidAndRole(roomId, RoleEnum.RoleAssistant.getValue());
  1111. if (assistants.isEmpty()) {
  1112. throw new ApiException(ErrorEnum.ERR_ASSISTANT_NOT_EXIST_IN_ROOM);
  1113. } else {
  1114. display += "?userId=" + assistants.get(0).getUid() + "?uri=";
  1115. roomDao.updateDisplayByRid(roomId, display);
  1116. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1117. sendDisplayMessage(display, roomMember);
  1118. } else {
  1119. DisplayMessage displayMessage = new DisplayMessage(display);
  1120. imHelper.publishMessage(userId, roomId, displayMessage);
  1121. }
  1122. log.info("change display to assistant: roomId={}, display={}", roomId, display);
  1123. }
  1124. } else if (displayEnum.equals(DisplayEnum.Screen)) {
  1125. display += "?userId=" + userId + "?uri=";
  1126. roomDao.updateDisplayByRid(roomId, display);
  1127. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1128. sendDisplayMessage(display, roomMember);
  1129. } else {
  1130. DisplayMessage displayMessage = new DisplayMessage(display);
  1131. imHelper.publishMessage(userId, roomId, displayMessage);
  1132. }
  1133. log.info("change display to screen: roomId={}, display={}", roomId, display);
  1134. } else if (displayEnum.equals(DisplayEnum.STUDENT)) {
  1135. display += "?userId=" + targetUserId + "?uri=" + uri;
  1136. roomDao.updateDisplayByRid(roomId, display);
  1137. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1138. sendDisplayMessage(display, roomMember);
  1139. } else {
  1140. DisplayMessage displayMessage = new DisplayMessage(display);
  1141. imHelper.publishMessage(userId, roomId, displayMessage);
  1142. }
  1143. log.info("change display to screen: roomId={}, display={}", roomId, display);
  1144. } else {
  1145. display += "?userId=" + userId + "?uri=" + uri;
  1146. // CheckUtils.checkArgument(uri != null, "uri must't be null");
  1147. // CheckUtils.checkArgument(whiteboardDao.findByRidAndWbid(roomId, uri).size() > 0, "whiteboard not exist");
  1148. roomDao.updateDisplayByRid(roomId, display);
  1149. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1150. sendDisplayMessage(display, roomMember);
  1151. } else {
  1152. DisplayMessage displayMessage = new DisplayMessage(display);
  1153. imHelper.publishMessage(userId, roomId, displayMessage);
  1154. }
  1155. }
  1156. log.info("result display in room: {}, type = {}, uri = {}", roomId, type, uri);
  1157. return true;
  1158. }
  1159. private void sendDisplayMessage(String display, RoomMember roomMember) throws Exception {
  1160. // 获取RTC服务提供方
  1161. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(TencentCloudRTCPlugin.PLUGIN_NAME);
  1162. // 腾讯云RTC服务
  1163. RTCRoomMessage.MessageContent.MessageContentBuilder action = RTCRoomMessage.MessageContent.builder()
  1164. .display(display)
  1165. .sendUserInfo(getSendUser(roomMember.getUid(),RoleEnum.getEnumByValue(roomMember.getRole())));
  1166. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  1167. .objectName(RTCRoomMessage.DISPLAY_MESSAGE)
  1168. .content(action.build())
  1169. .toChatRoomId(roomMember.getRid())
  1170. .fromUserId(roomMember.getUid())
  1171. .isIncludeSender(1)
  1172. .isPersisted(1)
  1173. .build();
  1174. pluginService.sendChatRoomMessage(roomMessage);
  1175. }
  1176. private RTCRoomMessage.MessageUser getSendUser(String userId,RoleEnum role) {
  1177. SysUser sysUser = sysUserFeignService.queryUserById(Integer.parseInt(userId));
  1178. RTCRoomMessage.MessageUser build = RTCRoomMessage.MessageUser.builder()
  1179. .sendUserId(userId)
  1180. .sendUserName(sysUser.getUsername())
  1181. .avatarUrl(sysUser.getAvatar())
  1182. .build();
  1183. if (role == RoleTeacher) {
  1184. build.setSendUserName(sysUser.getRealName());
  1185. }
  1186. return build;
  1187. }
  1188. @Override
  1189. @Transactional(rollbackFor = Exception.class)
  1190. public String createWhiteBoard(String roomId) throws Exception {
  1191. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1192. SysUser authUser = sysUserFeignService.queryUserInfo();
  1193. String userId = authUser.getId().toString();
  1194. log.info("createWhiteBoard: roomId = {}", roomId);
  1195. String wbRoom = IdentifierUtils.uuid();
  1196. WhiteBoardApiResultInfo resultInfo = whiteBoardHelper.create(wbRoom);
  1197. if (resultInfo.isSuccess()) {
  1198. String wbId = resultInfo.getData();
  1199. Date date = DateTimeUtils.currentUTC();
  1200. Room room = roomDao.findByRid(roomId);
  1201. int whiteboardNameIndex = room.getWhiteboardNameIndex() + 1;
  1202. String name = "白板" + whiteboardNameIndex;
  1203. roomDao.updateWhiteboardNameIndexByRid(roomId, whiteboardNameIndex);
  1204. Whiteboard wb = new Whiteboard();
  1205. wb.setRid(roomId);
  1206. wb.setWbRoom(wbRoom);
  1207. wb.setWbid(wbId);
  1208. wb.setName(name);
  1209. wb.setCreator(userId);
  1210. wb.setCreateDt(date);
  1211. wb.setCurPg(0);
  1212. whiteboardDao.save(wb);
  1213. WhiteboardMessage wbmsg = new WhiteboardMessage(WhiteboardMessage.Create);
  1214. wbmsg.setWhiteboardId(wbId);
  1215. wbmsg.setWhiteboardName(name);
  1216. imHelper.publishMessage(userId, roomId, wbmsg);
  1217. String display = "display://type=2?userId=" + userId + "?uri=" + Optional.ofNullable(wbId).orElse("");
  1218. roomDao.updateDisplayByRid(roomId, display);
  1219. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1220. String roomServiceProviter = getRoomServiceProvider(roomId);
  1221. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1222. sendDisplayMessage(display, roomMember);
  1223. } else {
  1224. DisplayMessage displayMessage = new DisplayMessage(display);
  1225. imHelper.publishMessage(userId, roomId, displayMessage, 1);
  1226. }
  1227. return wbId;
  1228. } else {
  1229. throw new ApiException(ErrorEnum.ERR_CREATE_WHITE_BOARD, resultInfo.getMsg());
  1230. }
  1231. }
  1232. @Override
  1233. @Transactional(rollbackFor = Exception.class)
  1234. public Boolean deleteWhiteboard(String roomId, String whiteBoardId) throws Exception {
  1235. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1236. CheckUtils.checkArgument(whiteBoardId != null, "whiteBoardId must't be null");
  1237. SysUser authUser = sysUserFeignService.queryUserInfo();
  1238. String userId = authUser.getId().toString();
  1239. List<Whiteboard> whiteboardList = whiteboardDao.findByRidAndWbid(roomId, whiteBoardId);
  1240. CheckUtils.checkArgument(whiteboardList.size() > 0, "whiteboard not exist");
  1241. Room room = roomDao.findByRid(roomId);
  1242. CheckUtils.checkArgument(room != null, "room not exist");
  1243. log.info("deleteWhiteboard: room={}, whiteBoardId={}", room, whiteBoardId);
  1244. String display = room.getDisplay();
  1245. if (display.contains("uri=" + whiteBoardId)) {
  1246. int result = roomDao.updateDisplayByRid(roomId, "");
  1247. log.info("clear room display, room: {}, result: {}", roomId, result);
  1248. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1249. String roomServiceProviter = getRoomServiceProvider(roomId);
  1250. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1251. sendDisplayMessage(display, roomMember);
  1252. } else {
  1253. DisplayMessage displayMessage = new DisplayMessage("");
  1254. imHelper.publishMessage(userId, roomId, displayMessage, 1);
  1255. }
  1256. } else {
  1257. log.info("no display to clean: room={}", room);
  1258. }
  1259. String wbRoom = whiteboardList.get(0).getWbRoom();
  1260. WhiteBoardApiResultInfo resultInfo = whiteBoardHelper.destroy(wbRoom);
  1261. if (resultInfo.isSuccess()) {
  1262. int result = whiteboardDao.deleteByWbid(whiteBoardId);
  1263. log.info("delete whiteboard: roomId = {}, whiteBoardId = {}, result = {}", roomId, whiteBoardId, result);
  1264. WhiteboardMessage wbmsg = new WhiteboardMessage(WhiteboardMessage.Delete);
  1265. wbmsg.setWhiteboardId(whiteBoardId);
  1266. imHelper.publishMessage(userId, roomId, wbmsg, 1);
  1267. return true;
  1268. } else {
  1269. throw new ApiException(ErrorEnum.ERR_DELETE_WHITE_BOARD, resultInfo.getMsg());
  1270. }
  1271. }
  1272. @Override
  1273. @Transactional(rollbackFor = Exception.class)
  1274. public List<RoomResult.WhiteboardResult> getWhiteboard(String roomId) throws Exception {
  1275. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1276. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  1277. List<Whiteboard> whiteboards = whiteboardDao.findByRid(roomId);
  1278. List<RoomResult.WhiteboardResult> result = new ArrayList<>();
  1279. for (Whiteboard wb : whiteboards) {
  1280. RoomResult.WhiteboardResult r = new RoomResult.WhiteboardResult();
  1281. r.setName(wb.getName());
  1282. r.setCurPg(wb.getCurPg());
  1283. r.setWhiteboardId(wb.getWbid());
  1284. result.add(r);
  1285. }
  1286. return result;
  1287. }
  1288. @Override
  1289. @Transactional(rollbackFor = Exception.class)
  1290. public Boolean turnWhiteBoardPage(String roomId, String whiteBoardId, int page) throws Exception {
  1291. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1292. CheckUtils.checkArgument(whiteBoardId != null, "whiteBoardId must't be null");
  1293. SysUser authUser = sysUserFeignService.queryUserInfo();
  1294. String userId = authUser.getId().toString();
  1295. Room room = roomDao.findByRid(roomId);
  1296. CheckUtils.checkArgument(room != null, "room not exist");
  1297. int result = whiteboardDao.updatePageByRidAndWbid(roomId, whiteBoardId, page);
  1298. log.info("turn page to: {}, room: {}, wb : {}; r: {}", page, roomId, whiteBoardId, result);
  1299. TurnPageMessage turnPageMessage = new TurnPageMessage(whiteBoardId, userId, page);
  1300. imHelper.publishMessage(userId, roomId, turnPageMessage);
  1301. return true;
  1302. }
  1303. @Override
  1304. @Transactional(rollbackFor = Exception.class)
  1305. public Boolean controlDevice(ReqDeviceControlData data) throws Exception {
  1306. // RTC服务方信息
  1307. if (StringUtils.isBlank(data.getServiceProvider())) {
  1308. // 课程信息
  1309. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(data.getRoomId().substring(1)));
  1310. if (Objects.isNull(courseSchedule)) {
  1311. throw new BizException("无效的课程编号");
  1312. }
  1313. data.setServiceProvider(courseSchedule.getServiceProvider());
  1314. // 课程老师信息
  1315. SysUser sysUser = sysUserFeignService.queryUserById(courseSchedule.getTeacherId());
  1316. if (Objects.nonNull(sysUser)) {
  1317. data.setSendUserId(sysUser.getId().toString());
  1318. data.setSendUserName(sysUser.getRealName());
  1319. data.setAvatar(sysUser.getAvatar());
  1320. }
  1321. }
  1322. String roomId = data.getRoomId();
  1323. String userId = data.getUserId();
  1324. DeviceTypeEnum typeEnum;
  1325. boolean enable;
  1326. if (data.getCameraOn() != null) {
  1327. typeEnum = DeviceTypeEnum.Camera;
  1328. enable = data.getCameraOn();
  1329. } else if (data.getMicrophoneOn() != null) {
  1330. typeEnum = DeviceTypeEnum.Microphone;
  1331. enable = data.getMicrophoneOn();
  1332. } else if (data.getMusicModeOn() != null) {
  1333. typeEnum = DeviceTypeEnum.MusicMode;
  1334. enable = data.getMusicModeOn();
  1335. } else if (data.getHandUpOn() != null) {
  1336. typeEnum = DeviceTypeEnum.HandUp;
  1337. enable = data.getHandUpOn();
  1338. } else if (data.getExamSongOn() != null) {
  1339. typeEnum = DeviceTypeEnum.ExamSong;
  1340. enable = data.getExamSongOn();
  1341. } else if (data.getMusicScoreOn() != null) {
  1342. typeEnum = DeviceTypeEnum.MusicScore;
  1343. enable = data.getMusicScoreOn();
  1344. if (enable) {
  1345. //保存伴奏音量
  1346. roomDao.updateSoundVolumeById(roomId, data.getSoundVolume() == null ? 0 : data.getSoundVolume());
  1347. }
  1348. } else if (data.getAccompanimentOn() != null) {
  1349. typeEnum = DeviceTypeEnum.MusicScoreAccompaniment;
  1350. enable = data.getAccompanimentOn();
  1351. if (enable) {
  1352. //保存伴奏音量
  1353. roomDao.updateSoundVolumeById(roomId, data.getSoundVolume() == null ? 0 : data.getSoundVolume());
  1354. }
  1355. } else {
  1356. throw new ApiException(ErrorEnum.ERR_REQUEST_PARA_ERR);
  1357. }
  1358. SysUser authUser = sysUserFeignService.queryUserInfo();
  1359. log.info("controlDevice: userId = {}, typeEnum = {}, enable = {} ,roomId = {}", userId, typeEnum, enable, roomId);
  1360. // RTC服务对象
  1361. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(data.getServiceProvider());
  1362. // 通知消息
  1363. RTCRoomMessage.MessageContent notifyContent = RTCRoomMessage.MessageContent
  1364. .builder()
  1365. .type(typeEnum.ordinal())
  1366. .enable(enable)
  1367. .targetId(userId)
  1368. .targetName(Optional.ofNullable(data.getUserName()).orElse(authUser.getUsername()))
  1369. .songId(Optional.ofNullable(data.getMusicScoreAccompanimentId()).map(String::valueOf).orElse(null))
  1370. .songVolume(data.getSoundVolume())
  1371. .sendUserInfo(RTCRoomMessage.MessageUser.builder()
  1372. .sendUserId(data.getSendUserId())
  1373. .sendUserName(data.getSendUserName())
  1374. .avatarUrl(data.getAvatar())
  1375. .build())
  1376. .build();
  1377. // 消息内容
  1378. /*RTCRoomMessage.MessageContent messageContent = RTCRoomMessage.MessageContent
  1379. .builder()
  1380. .type(typeEnum.ordinal())
  1381. .enable(enable)
  1382. .sendUserInfo(RTCRoomMessage.MessageUser.builder()
  1383. .sendUserId(userId)
  1384. .sendUserName(authUser.getUsername())
  1385. .avatarUrl(authUser.getAvatar())
  1386. .build())
  1387. .build();*/
  1388. // 腾讯云消息推送
  1389. RTCRoomMessage message = RTCRoomMessage.builder()
  1390. .objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE)
  1391. .fromUserId(userId)
  1392. .toChatRoomId(roomId)
  1393. .content(notifyContent)
  1394. .isPersisted(1)
  1395. .isIncludeSender(0)
  1396. .build();
  1397. if (enable) {
  1398. if (typeEnum.equals(DeviceTypeEnum.ExamSong)) {
  1399. long scheduleId = Long.parseLong(roomId.substring(1));
  1400. ExamSongDownloadData msg;
  1401. String examJson = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(scheduleId, Integer.parseInt(userId));
  1402. if (StringUtils.isEmpty(examJson)) {
  1403. throw new BizException("学员伴奏信息异常");
  1404. } else {
  1405. msg = JSON.parseObject(examJson, ExamSongDownloadData.class);
  1406. msg.setEnable(enable);
  1407. }
  1408. courseScheduleStudentPaymentDao.adjustExamSong(scheduleId, Integer.parseInt(userId), JSON.toJSONString(msg));
  1409. DeviceStateChangedMessage deviceResourceMessage = new DeviceStateChangedMessage(typeEnum.ordinal(), enable);
  1410. deviceResourceMessage.setUserId(userId);
  1411. // 消息发送
  1412. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  1413. // 腾讯云推送
  1414. pluginService.sendChatRoomMessage(message.objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE).content(notifyContent));
  1415. } else {
  1416. // 融云推送
  1417. imHelper.publishMessage(authUser.getId().toString(), roomId, deviceResourceMessage, 1);
  1418. }
  1419. } else if (typeEnum.equals(DeviceTypeEnum.MusicScore)) {
  1420. long scheduleId = Long.parseLong(roomId.substring(1));
  1421. //关闭所有曲目播放
  1422. courseScheduleStudentMusicScoreDao.closePlayStatus(scheduleId, Integer.parseInt(userId), null);
  1423. DeviceStateChangedMessage deviceResourceMessage = new DeviceStateChangedMessage(typeEnum.ordinal(), enable);
  1424. deviceResourceMessage.setMusicScoreAccompanimentId(data.getMusicScoreAccompanimentId());
  1425. deviceResourceMessage.setUserId(userId);
  1426. deviceResourceMessage.setSoundVolume(data.getSoundVolume());
  1427. //原音
  1428. courseScheduleStudentMusicScoreDao.openPlayStatus(scheduleId, data.getMusicScoreAccompanimentId(), Integer.parseInt(userId));
  1429. // 消息发送
  1430. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  1431. // 腾讯云推送
  1432. pluginService.sendChatRoomMessage(message.objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE).content(notifyContent));
  1433. } else {
  1434. // 融云推送
  1435. imHelper.publishMessage(authUser.getId().toString(), roomId, deviceResourceMessage, 1);
  1436. }
  1437. } else if (typeEnum.equals(DeviceTypeEnum.MusicScoreAccompaniment)) {
  1438. long scheduleId = Long.parseLong(roomId.substring(1));
  1439. //关闭所有曲目播放
  1440. courseScheduleStudentMusicScoreDao.closePlayStatus(scheduleId, Integer.parseInt(userId), null);
  1441. courseScheduleStudentMusicScoreDao.openAccompanimentPlayStatus(scheduleId, data.getMusicScoreAccompanimentId(), Integer.parseInt(userId));
  1442. DeviceStateChangedMessage deviceResourceMessage = new DeviceStateChangedMessage(typeEnum.ordinal(), enable);
  1443. deviceResourceMessage.setMusicScoreAccompanimentId(data.getMusicScoreAccompanimentId());
  1444. deviceResourceMessage.setUserId(userId);
  1445. deviceResourceMessage.setSoundVolume(data.getSoundVolume());// 消息发送
  1446. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  1447. // 腾讯云推送
  1448. pluginService.sendChatRoomMessage(message.objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE).content(notifyContent));
  1449. } else {
  1450. // 融云推送
  1451. imHelper.publishMessage(authUser.getId().toString(), roomId, deviceResourceMessage, 1);
  1452. }
  1453. } else {
  1454. String ticket = IdentifierUtils.uuid();
  1455. ControlDeviceTaskInfo taskInfo = new ControlDeviceTaskInfo();
  1456. taskInfo.setRoomId(roomId);
  1457. taskInfo.setTypeEnum(typeEnum);
  1458. taskInfo.setOnOff(true);
  1459. taskInfo.setApplyUserId(authUser.getId().toString());
  1460. taskInfo.setTargetUserId(userId);
  1461. taskInfo.setTicket(ticket);
  1462. scheduleManager.addTask(taskInfo);
  1463. ControlDeviceNotifyMessage msg = new ControlDeviceNotifyMessage(ActionEnum.Invite.ordinal());
  1464. msg.setTicket(ticket);
  1465. msg.setType(taskInfo.getTypeEnum().ordinal());
  1466. msg.setOpUserId(authUser.getId().toString());
  1467. msg.setOpUserName(authUser.getUsername());
  1468. // 发送消息
  1469. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  1470. // 腾讯消息
  1471. pluginService.sendChatRoomMessage(message.objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE).content(notifyContent));
  1472. } else {
  1473. // 融云消息
  1474. imHelper.publishMessage(authUser.getId().toString(), userId, roomId, msg);
  1475. }
  1476. }
  1477. } else {
  1478. if (typeEnum.equals(DeviceTypeEnum.Camera)) {
  1479. roomMemberDao.updateCameraByRidAndUid(roomId, userId, false);
  1480. } else if (typeEnum.equals(DeviceTypeEnum.Microphone)) {
  1481. roomMemberDao.updateMicByRidAndUid(roomId, userId, false);
  1482. } else if (typeEnum.equals(DeviceTypeEnum.HandUp)) {
  1483. roomMemberDao.updateHandByRidAndUid(roomId, userId, false);
  1484. } else if (typeEnum.equals(DeviceTypeEnum.ExamSong)) {
  1485. long scheduleId = Long.parseLong(roomId.substring(1));
  1486. ExamSongDownloadData msg;
  1487. String examJson = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(scheduleId, Integer.parseInt(userId));
  1488. if (StringUtils.isEmpty(examJson)) {
  1489. throw new BizException("学员伴奏信息异常");
  1490. } else {
  1491. msg = JSON.parseObject(examJson, ExamSongDownloadData.class);
  1492. msg.setEnable(enable);
  1493. }
  1494. courseScheduleStudentPaymentDao.adjustExamSong(scheduleId, Integer.parseInt(userId), JSON.toJSONString(msg));
  1495. } else if (typeEnum.equals(DeviceTypeEnum.MusicScore)) {
  1496. long scheduleId = Long.parseLong(roomId.substring(1));
  1497. //关闭所有曲目播放
  1498. courseScheduleStudentMusicScoreDao.closePlayStatus(scheduleId, Integer.parseInt(userId), null);
  1499. } else if (typeEnum.equals(DeviceTypeEnum.MusicScoreAccompaniment)) {
  1500. long scheduleId = Long.parseLong(roomId.substring(1));
  1501. //关闭所有曲目播放
  1502. courseScheduleStudentMusicScoreDao.closePlayStatus(scheduleId, Integer.parseInt(userId), null);
  1503. } else {
  1504. roomMemberDao.updateMusicByRidAndUid(roomId, userId, false);
  1505. }
  1506. DeviceStateChangedMessage deviceResourceMessage = new DeviceStateChangedMessage(typeEnum.ordinal(), false);
  1507. deviceResourceMessage.setUserId(userId);
  1508. UserInfo userInfo = userDao.findByUid(userId);
  1509. if (userInfo != null) {
  1510. deviceResourceMessage.setUserName(userInfo.getName());
  1511. }
  1512. // 发送消息
  1513. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  1514. // 腾讯消息
  1515. pluginService.sendChatRoomMessage(message.objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE).content(notifyContent));
  1516. } else {
  1517. // 融云消息
  1518. imHelper.publishMessage(authUser.getId().toString(), roomId, deviceResourceMessage, 1);
  1519. }
  1520. }
  1521. return true;
  1522. }
  1523. @Override
  1524. @Transactional(rollbackFor = Exception.class)
  1525. public Boolean batchControlDevice(ReqDeviceControlData data) throws Exception {
  1526. // 课程ID
  1527. long courseScheduleId = Long.parseLong(data.getRoomId().substring(1));
  1528. CourseSchedule courseSchedule = courseScheduleDao.get(courseScheduleId);
  1529. if (Objects.isNull(courseSchedule)) {
  1530. throw new BizException("无效的课程编号");
  1531. }
  1532. data.setServiceProvider(courseSchedule.getServiceProvider());
  1533. // 同步全员静音状态
  1534. if (Objects.nonNull(data.getMicrophoneOn())) {
  1535. courseScheduleDao.updateGroupMuteAllStatus(courseScheduleId, !data.getMicrophoneOn());
  1536. }
  1537. // 课程老师信息
  1538. SysUser sysUser = sysUserFeignService.queryUserById(courseSchedule.getTeacherId());
  1539. if (Objects.nonNull(sysUser)) {
  1540. data.setSendUserId(sysUser.getId().toString());
  1541. data.setSendUserName(sysUser.getRealName());
  1542. data.setAvatar(sysUser.getAvatar());
  1543. }
  1544. if (data.getExamSongOn() != null || data.getMusicScoreOn() != null || data.getAccompanimentOn() != null) {
  1545. List<BasicUserDto> students = courseScheduleStudentPaymentDao.findStudents(courseScheduleId);
  1546. for (BasicUserDto e : students) {
  1547. data.setUserId(e.getUserId().toString());
  1548. data.setUserName(e.getName());
  1549. controlDevice(data);
  1550. }
  1551. return true;
  1552. }
  1553. List<RoomMember> roomMembers;
  1554. if (StringUtils.isNotEmpty(data.getUserId())) {
  1555. roomMembers = new ArrayList<>();
  1556. String[] split = data.getUserId().split(",");
  1557. for (int i = 0; i < split.length; i++) {
  1558. roomMembers.add(new RoomMember(split[i]));
  1559. }
  1560. } else {
  1561. roomMembers = roomMemberDao.findByRidAndRole(data.getRoomId(), RoleStudent.getValue());
  1562. }
  1563. if (roomMembers.size() == 0) {
  1564. return false;
  1565. }
  1566. for (RoomMember e : roomMembers) {
  1567. data.setUserId(e.getUid());
  1568. controlDevice(data);
  1569. }
  1570. boolean enable;
  1571. if (data.getCameraOn() != null) {
  1572. enable = data.getCameraOn();
  1573. roomMemberDao.updateCameraByRidAndRole(data.getRoomId(), RoleStudent.getValue(), enable);
  1574. } else if (data.getMicrophoneOn() != null) {
  1575. enable = data.getMicrophoneOn();
  1576. roomMemberDao.updateMicByRidAndRole(data.getRoomId(), RoleStudent.getValue(), enable);
  1577. } else if (data.getMusicModeOn() != null) {
  1578. enable = data.getMusicModeOn();
  1579. roomMemberDao.updateMusicByRidAndRole(data.getRoomId(), RoleStudent.getValue(), enable);
  1580. } else if (data.getHandUpOn() != null) {
  1581. enable = data.getHandUpOn();
  1582. roomMemberDao.updateHandByRidAndRole(data.getRoomId(), RoleStudent.getValue(), enable);
  1583. } else
  1584. return true;
  1585. return true;
  1586. }
  1587. @Override
  1588. @Transactional(rollbackFor = Exception.class)
  1589. public Boolean approveControlDevice(ReqDeviceControlData data) throws Exception {
  1590. String ticket = data.getTicket();
  1591. String roomId = data.getRoomId();
  1592. CheckUtils.checkArgument(ticket != null, "ticket must't be null");
  1593. SysUser authUser = sysUserFeignService.queryUserInfo();
  1594. String userId = authUser.getId().toString();
  1595. log.info("approveControlDevice: ticket={}", ticket);
  1596. ControlDeviceTaskInfo taskInfo = (ControlDeviceTaskInfo) scheduleManager.executeTask(ticket);
  1597. if (taskInfo.getTypeEnum().equals(DeviceTypeEnum.Camera)) {
  1598. roomMemberDao.updateCameraByRidAndUid(roomId, userId, taskInfo.isOnOff());
  1599. } else if (taskInfo.getTypeEnum().equals(DeviceTypeEnum.ExamSong)) {
  1600. long scheduleId = Long.parseLong(roomId.substring(1));
  1601. ExamSongDownloadData msg;
  1602. String examJson = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(scheduleId, authUser.getId());
  1603. if (StringUtils.isEmpty(examJson)) {
  1604. throw new BizException("学员伴奏信息异常");
  1605. } else {
  1606. msg = JSON.parseObject(examJson, ExamSongDownloadData.class);
  1607. msg.setEnable(true);
  1608. }
  1609. courseScheduleStudentPaymentDao.adjustExamSong(scheduleId, authUser.getId(), JSON.toJSONString(msg));
  1610. } else {
  1611. roomMemberDao.updateMicByRidAndUid(roomId, userId, taskInfo.isOnOff());
  1612. }
  1613. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1614. String roomServiceProviter = getRoomServiceProvider(roomId);
  1615. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1616. // 获取RTC服务提供方
  1617. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(TencentCloudRTCPlugin.PLUGIN_NAME);
  1618. // 腾讯云RTC服务
  1619. RTCRoomMessage.MessageContent.MessageContentBuilder action = RTCRoomMessage.MessageContent.builder()
  1620. .type(ActionEnum.Approve.ordinal())
  1621. .enable(taskInfo.isOnOff())
  1622. .targetId(userId)
  1623. .targetName(authUser.getUsername())
  1624. .sendUserInfo(getSendUser(taskInfo.getApplyUserId(), RoleTeacher));
  1625. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  1626. .objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE)
  1627. .content(action.build())
  1628. .toChatRoomId(roomMember.getRid())
  1629. .fromUserId(roomMember.getUid())
  1630. .isIncludeSender(1)
  1631. .isPersisted(1)
  1632. .build();
  1633. pluginService.sendChatRoomMessage(roomMessage);
  1634. // 腾讯云RTC服务
  1635. action = RTCRoomMessage.MessageContent.builder()
  1636. .type(ActionEnum.Approve.ordinal())
  1637. .enable(taskInfo.isOnOff())
  1638. .sendUserInfo(getSendUser(roomMember.getUid(),RoleEnum.getEnumByValue(roomMember.getRole())));
  1639. // 腾讯云消息推送
  1640. RTCRoomMessage message = RTCRoomMessage.builder()
  1641. .objectName(RTCRoomMessage.DEVICE_MESSAGE)
  1642. .fromUserId(userId)
  1643. .toChatRoomId(roomId)
  1644. .content(action.build())
  1645. .isPersisted(1)
  1646. .isIncludeSender(0)
  1647. .build();
  1648. pluginService.sendChatRoomMessage(message);
  1649. } else {
  1650. ControlDeviceNotifyMessage msg = new ControlDeviceNotifyMessage(ActionEnum.Approve.ordinal());
  1651. msg.setType(taskInfo.getTypeEnum().ordinal());
  1652. msg.setOpUserId(userId);
  1653. msg.setOpUserName(authUser.getUsername());
  1654. imHelper.publishMessage(userId, taskInfo.getApplyUserId(), roomId, msg);
  1655. DeviceStateChangedMessage deviceResourceMessage = new DeviceStateChangedMessage(taskInfo.getTypeEnum().ordinal(), taskInfo.isOnOff());
  1656. deviceResourceMessage.setUserId(userId);
  1657. imHelper.publishMessage(userId, roomId, deviceResourceMessage, 1);
  1658. }
  1659. return true;
  1660. }
  1661. @Override
  1662. @Transactional(rollbackFor = Exception.class)
  1663. public Boolean rejectControlDevice(String roomId, String ticket) throws Exception {
  1664. CheckUtils.checkArgument(ticket != null, "ticket must't be null");
  1665. SysUser authUser = sysUserFeignService.queryUserInfo();
  1666. String userId = authUser.getId().toString();
  1667. log.info("rejectControlDevice: ticket={}", ticket);
  1668. ControlDeviceTaskInfo taskInfo = (ControlDeviceTaskInfo) scheduleManager.executeTask(ticket);
  1669. ControlDeviceNotifyMessage msg = new ControlDeviceNotifyMessage(ActionEnum.Reject.ordinal());
  1670. msg.setType(taskInfo.getTypeEnum().ordinal());
  1671. msg.setOpUserId(userId);
  1672. msg.setOpUserName(authUser.getUsername());
  1673. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1674. String roomServiceProviter = getRoomServiceProvider(roomId);
  1675. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  1676. // 获取RTC服务提供方
  1677. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(TencentCloudRTCPlugin.PLUGIN_NAME);
  1678. RTCRoomMessage.MessageContent.MessageContentBuilder action = RTCRoomMessage.MessageContent.builder()
  1679. .type(ActionEnum.Reject.ordinal())
  1680. .enable(taskInfo.isOnOff())
  1681. .targetId(userId)
  1682. .targetName(authUser.getUsername())
  1683. .sendUserInfo(getSendUser(taskInfo.getApplyUserId(), RoleTeacher));
  1684. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  1685. .objectName(RTCRoomMessage.CONTROL_DEVICE_NOTIFY_MESSAGE)
  1686. .content(action.build())
  1687. .toChatRoomId(roomMember.getRid())
  1688. .fromUserId(roomMember.getUid())
  1689. .isIncludeSender(1)
  1690. .isPersisted(1)
  1691. .build();
  1692. pluginService.sendChatRoomMessage(roomMessage);
  1693. } else {
  1694. imHelper.publishMessage(userId, taskInfo.getApplyUserId(), roomId, msg);
  1695. }
  1696. return true;
  1697. }
  1698. @Override
  1699. @Transactional(rollbackFor = Exception.class)
  1700. public Boolean syncDeviceState(ReqDeviceControlData data) throws Exception {
  1701. String roomId = data.getRoomId();
  1702. DeviceTypeEnum type;
  1703. boolean enable;
  1704. if (data.getCameraOn() != null) {
  1705. type = DeviceTypeEnum.Camera;
  1706. enable = data.getCameraOn();
  1707. } else if (data.getMicrophoneOn() != null) {
  1708. type = DeviceTypeEnum.Microphone;
  1709. enable = data.getMicrophoneOn();
  1710. } else if (data.getMusicModeOn() != null) {
  1711. type = DeviceTypeEnum.MusicMode;
  1712. enable = data.getMusicModeOn();
  1713. } else if (data.getHandUpOn() != null) {
  1714. type = DeviceTypeEnum.HandUp;
  1715. enable = data.getHandUpOn();
  1716. } else if (data.getExamSongOn() != null) {
  1717. type = DeviceTypeEnum.ExamSong;
  1718. enable = data.getExamSongOn();
  1719. } else {
  1720. throw new ApiException(ErrorEnum.ERR_REQUEST_PARA_ERR);
  1721. }
  1722. SysUser authUser = sysUserFeignService.queryUserInfo();
  1723. String userId = authUser.getId().toString();
  1724. DeviceStateChangedMessage deviceResourceMessage = new DeviceStateChangedMessage(type.ordinal(), enable);
  1725. if (type.equals(DeviceTypeEnum.Camera)) {
  1726. roomMemberDao.updateCameraByRidAndUid(roomId, userId, enable);
  1727. } else if (type.equals(DeviceTypeEnum.Microphone)) {
  1728. roomMemberDao.updateMicByRidAndUid(roomId, userId, enable);
  1729. } else if (type.equals(DeviceTypeEnum.HandUp)) {
  1730. roomMemberDao.updateHandByRidAndUid(roomId, userId, enable);
  1731. } else if (type.equals(DeviceTypeEnum.ExamSong)) {
  1732. long scheduleId = Long.parseLong(roomId.substring(1));
  1733. ExamSongDownloadData msg;
  1734. String examJson = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(scheduleId, authUser.getId());
  1735. if (StringUtils.isEmpty(examJson)) {
  1736. throw new BizException("学员伴奏信息异常");
  1737. } else {
  1738. msg = JSON.parseObject(examJson, ExamSongDownloadData.class);
  1739. msg.setEnable(enable);
  1740. }
  1741. courseScheduleStudentPaymentDao.adjustExamSong(scheduleId, authUser.getId(), JSON.toJSONString(msg));
  1742. } else {
  1743. roomMemberDao.updateMusicByRidAndUid(roomId, userId, enable);
  1744. }
  1745. Room room = roomDao.findByRid(roomId);
  1746. //看了下日志,存在退出房间后短时间内请求该接口的情况
  1747. if(Objects.nonNull(room)){
  1748. deviceResourceMessage.setSoundVolume(room.getSoundVolume());
  1749. }
  1750. deviceResourceMessage.setUserId(userId);
  1751. // 查询课程信息
  1752. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(roomId.substring(1)));
  1753. if (Objects.isNull(courseSchedule)) {
  1754. throw new BizException("无效的课程ID");
  1755. }
  1756. data.setServiceProvider(courseSchedule.getServiceProvider());
  1757. // RTC服务对象
  1758. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(data.getServiceProvider());
  1759. // 消息内容
  1760. RTCRoomMessage.MessageContent messageContent = RTCRoomMessage.MessageContent
  1761. .builder()
  1762. .type(deviceResourceMessage.getType())
  1763. .enable(deviceResourceMessage.isEnable())
  1764. .sendUserInfo(getSendUser(authUser.getId().toString(), RoleTeacher))
  1765. .build();
  1766. // 腾讯云消息推送
  1767. RTCRoomMessage message = RTCRoomMessage.builder()
  1768. .objectName(RTCRoomMessage.DEVICE_MESSAGE)
  1769. .fromUserId(userId)
  1770. .toChatRoomId(roomId)
  1771. .content(messageContent)
  1772. .isPersisted(1)
  1773. .isIncludeSender(0)
  1774. .build();
  1775. if (TencentCloudRTCPlugin.PLUGIN_NAME.matches(data.getServiceProvider())) {
  1776. // 发送消息
  1777. pluginService.sendChatRoomMessage(message);
  1778. } else {
  1779. // 融云消息推送
  1780. imHelper.publishMessage(userId, roomId, deviceResourceMessage, 1);
  1781. }
  1782. log.info("syncDeviceState : {}, {}", roomId, enable);
  1783. return true;
  1784. }
  1785. @Override
  1786. @Transactional(rollbackFor = Exception.class)
  1787. public List<RoomResult.MemberResult> getMembers(String roomId, String userId) throws Exception {
  1788. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1789. List<RoomMember> roomMemberList = roomMemberDao.findByRid(roomId);
  1790. // 参数过滤
  1791. if (StringUtils.isNotBlank(userId)) {
  1792. roomMemberList = roomMemberList.stream().filter(x -> x.getUid().equals(userId)).collect(Collectors.toList());
  1793. }
  1794. // 网络课用户信息
  1795. if (CollectionUtils.isNotEmpty(roomMemberList)) {
  1796. // 当前房间用户去重
  1797. Collection<RoomMember> roomMembers = roomMemberList.stream()
  1798. .collect(Collectors.toMap(RoomMember::getUid, Function.identity(), (o, n) -> n)).values();
  1799. // 重置房间用户信息
  1800. roomMemberList = Lists.newArrayList(roomMembers);
  1801. List<CourseScheduleStudentMusicScore> scheduleStudentMusicScores = courseScheduleStudentMusicScoreDao.queryByScoreIdAndCourseId(null, Long.parseLong(roomId.substring(1)), null, null, null);
  1802. RoomResult roomResult = new RoomResult();
  1803. Set<String> userIds = roomMemberList.stream().map(RoomMember::getUid).collect(Collectors.toSet());
  1804. Map<Integer, String> midiMap = MapUtil.convertMybatisMap(courseScheduleStudentPaymentDao.queryMidiByUserIdsAndCourseId(userIds, roomId.substring(1)));
  1805. Map<Integer, String> examSongMap = MapUtil.convertMybatisMap(courseScheduleStudentPaymentDao.queryExamSongByUserIdsAndCourseId(userIds, roomId.substring(1)));
  1806. roomResult.setMembers(roomMemberList, midiMap, examSongMap, scheduleStudentMusicScores);
  1807. // 全员静音开启状态
  1808. CourseSchedule courseSchedule = courseScheduleDao.get(Long.parseLong(roomId.substring(1)));
  1809. if (Optional.ofNullable(courseSchedule.getMuteAll()).orElse(false)
  1810. && TencentCloudRTCPlugin.PLUGIN_NAME.equals(courseSchedule.getServiceProvider())) {
  1811. for (RoomResult.MemberResult item : roomResult.getMembers()) {
  1812. // 重置学生用户当前静音状态
  1813. if (RoleStudent.getValue() == item.getRole()) {
  1814. item.setMicrophone(false);
  1815. }
  1816. }
  1817. }
  1818. return roomResult.getMembers();
  1819. }
  1820. return null;
  1821. }
  1822. @Override
  1823. @Transactional(rollbackFor = Exception.class)
  1824. public Boolean applySpeech(String roomId) throws Exception {
  1825. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1826. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  1827. SysUser authUser = sysUserFeignService.queryUserInfo();
  1828. String userId = authUser.getId().toString();
  1829. List<RoomMember> assistants = roomMemberDao.findByRidAndRole(roomId, RoleEnum.RoleAssistant.getValue());
  1830. if (assistants.isEmpty()) {
  1831. throw new ApiException(ErrorEnum.ERR_ASSISTANT_NOT_EXIST_IN_ROOM);
  1832. }
  1833. String ticket = IdentifierUtils.uuid();
  1834. ScheduledTaskInfo scheduledTaskInfo = new ScheduledTaskInfo();
  1835. scheduledTaskInfo.setTicket(ticket);
  1836. scheduledTaskInfo.setRoomId(roomId);
  1837. scheduledTaskInfo.setApplyUserId(userId);
  1838. scheduledTaskInfo.setTargetUserId(assistants.get(0).getUid());
  1839. scheduleManager.addTask(scheduledTaskInfo);
  1840. log.info("applySpeech: task = {}", scheduledTaskInfo);
  1841. ApplyForSpeechMessage msg = new ApplyForSpeechMessage();
  1842. msg.setTicket(ticket);
  1843. msg.setReqUserId(userId);
  1844. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, assistants.get(0).getUid(), roomId, msg);
  1845. log.info("apply for speech: {}, task = {}", roomId, scheduledTaskInfo);
  1846. if (resultInfo.isSuccess()) {
  1847. return true;
  1848. } else {
  1849. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  1850. }
  1851. }
  1852. @Override
  1853. @Transactional(rollbackFor = Exception.class)
  1854. public Boolean approveSpeech(String roomId, String ticket) throws Exception {
  1855. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1856. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  1857. SysUser authUser = sysUserFeignService.queryUserInfo();
  1858. String userId = authUser.getId().toString();
  1859. int count = roomMemberDao.countByRidAndExcludeRole(roomId, RoleEnum.RoleAudience.getValue());
  1860. if (count == roomProperties.getMaxCount()) {
  1861. log.error("approveSpeech error: roomId = {}, ticket={}", roomId, ticket);
  1862. throw new ApiException(ErrorEnum.ERR_OVER_MAX_COUNT);
  1863. }
  1864. ScheduledTaskInfo taskInfo = scheduleManager.executeTask(ticket);
  1865. log.info("approveSpeech: task = {}", taskInfo);
  1866. roomMemberDao.updateRoleByRidAndUid(roomId, taskInfo.getApplyUserId(), RoleStudent.getValue());
  1867. SpeechResultMessage msg = new SpeechResultMessage(SpeechResultMessage.Action_Approve);
  1868. UserInfo userInfo = userDao.findByUid(taskInfo.getApplyUserId());
  1869. msg.setOpUserId(userId);
  1870. msg.setOpUserName(authUser.getUsername());
  1871. msg.setReqUserId(taskInfo.getApplyUserId());
  1872. if (userInfo != null) {
  1873. msg.setReqUserName(userInfo.getName());
  1874. }
  1875. msg.setRole(RoleStudent.getValue());
  1876. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, taskInfo.getApplyUserId(), roomId, msg);
  1877. if (!resultInfo.isSuccess()) {
  1878. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  1879. }
  1880. RoleChangedMessage rcMsg = new RoleChangedMessage(userId);
  1881. List<RoleChangedMessage.ChangedUser> changedUserList = new ArrayList<>();
  1882. RoleChangedMessage.ChangedUser user = new RoleChangedMessage.ChangedUser(taskInfo.getApplyUserId(), RoleStudent.getValue());
  1883. if (userInfo != null) {
  1884. user.setUserName(userInfo.getName());
  1885. }
  1886. changedUserList.add(user);
  1887. rcMsg.setUsers(changedUserList);
  1888. imHelper.publishMessage(userId, roomId, rcMsg, 1);
  1889. return true;
  1890. }
  1891. @Override
  1892. @Transactional(rollbackFor = Exception.class)
  1893. public Boolean rejectSpeech(String roomId, String ticket) throws Exception {
  1894. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1895. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  1896. SysUser authUser = sysUserFeignService.queryUserInfo();
  1897. String userId = authUser.getId().toString();
  1898. ScheduledTaskInfo taskInfo = scheduleManager.executeTask(ticket);
  1899. log.info("rejectSpeech: task = {}", taskInfo);
  1900. SpeechResultMessage msg = new SpeechResultMessage(SpeechResultMessage.Action_Reject);
  1901. msg.setOpUserId(userId);
  1902. msg.setOpUserName(authUser.getUsername());
  1903. msg.setRole(RoleStudent.getValue());
  1904. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, taskInfo.getApplyUserId(), roomId, msg);
  1905. if (resultInfo.isSuccess()) {
  1906. return true;
  1907. } else {
  1908. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  1909. }
  1910. }
  1911. public void checkOverMax(String roomId, RoomMember targetUser, int targetRole) {
  1912. if (RoleEnum.getEnumByValue(targetUser.getRole()).equals(RoleEnum.RoleAudience)) {
  1913. int count = roomMemberDao.countByRidAndExcludeRole(roomId, RoleEnum.RoleAudience.getValue());
  1914. if (count == roomProperties.getMaxCount()) {
  1915. log.error("assign error: roomId = {}, userId = {}, role = {}", roomId, targetUser.getRid(), targetUser.getRole());
  1916. throw new ApiException(ErrorEnum.ERR_OVER_MAX_COUNT);
  1917. }
  1918. } else if (targetRole > targetUser.getRole()) {
  1919. throw new ApiException(ErrorEnum.ERR_DOWNGRADE_ROLE);
  1920. }
  1921. }
  1922. @Override
  1923. @Transactional(rollbackFor = Exception.class)
  1924. public Boolean transfer(String roomId, String userId) throws Exception {
  1925. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1926. CheckUtils.checkArgument(userId != null, "userId must't be null");
  1927. CheckUtils.checkArgument(!userId.equals(userId), "can't set self role");
  1928. log.info("transfer: roomId = {}, userId = {}", roomId, userId);
  1929. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  1930. if (roomMember == null) {
  1931. log.error("assistant transfer error: {} toUser = {}, opUser={}", roomId, userId, userId);
  1932. throw new ApiException(ErrorEnum.ERR_USER_NOT_EXIST_IN_ROOM);
  1933. }
  1934. Room room = roomDao.findByRid(roomId);
  1935. if (room == null) {
  1936. log.error("assistant transfer error: {} toUser = {}, opUser={}", roomId, userId, userId);
  1937. throw new ApiException(ErrorEnum.ERR_ROOM_NOT_EXIST);
  1938. }
  1939. if (isUserDisplay(room, userId) || isUserDisplay(room, userId)) {
  1940. updateDisplay(roomId, userId, "", 1);
  1941. } else {
  1942. log.info("don't update display: room={}", room);
  1943. }
  1944. roomMemberDao.updateRoleByRidAndUid(roomId, userId, RoleStudent.getValue());
  1945. roomMemberDao.updateRoleByRidAndUid(roomId, userId, RoleEnum.RoleAssistant.getValue());
  1946. AssistantTransferMessage msg = new AssistantTransferMessage();
  1947. msg.setOpUserId(userId);
  1948. msg.setToUserId(userId);
  1949. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, roomId, msg, 1);
  1950. if (resultInfo.isSuccess()) {
  1951. return true;
  1952. } else {
  1953. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  1954. }
  1955. }
  1956. @Override
  1957. @Transactional(rollbackFor = Exception.class)
  1958. public Boolean inviteUpgradeRole(String roomId, String targetUserId, int targetRole) throws Exception {
  1959. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1960. CheckUtils.checkArgument(targetUserId != null, "userId must't be null");
  1961. CheckUtils.checkArgument(roomMemberDao.existsByRidAndUid(roomId, targetUserId), "room member not exist");
  1962. SysUser authUser = sysUserFeignService.queryUserInfo();
  1963. String userId = authUser.getId().toString();
  1964. log.info("inviteUpgradeRole roomId = {}, targetUserId = {}, targetRole = {}", roomId, targetUserId, targetRole);
  1965. RoomMember targetUser = roomMemberDao.findByRidAndUid(roomId, targetUserId);
  1966. if (targetUser == null) {
  1967. throw new ApiException(ErrorEnum.ERR_USER_NOT_EXIST_IN_ROOM);
  1968. }
  1969. checkOverMax(roomId, targetUser, targetRole);
  1970. String ticket = IdentifierUtils.uuid();
  1971. UpgradeRoleTaskInfo taskInfo = new UpgradeRoleTaskInfo();
  1972. taskInfo.setTicket(ticket);
  1973. taskInfo.setRoomId(roomId);
  1974. taskInfo.setApplyUserId(userId);
  1975. taskInfo.setTargetUserId(targetUserId);
  1976. taskInfo.setRole(RoleEnum.getEnumByValue(targetRole));
  1977. scheduleManager.addTask(taskInfo);
  1978. UpgradeRoleMessage msg = new UpgradeRoleMessage(ActionEnum.Invite.ordinal());
  1979. msg.setTicket(ticket);
  1980. msg.setOpUserId(userId);
  1981. msg.setOpUserName(authUser.getUsername());
  1982. msg.setRole(targetRole);
  1983. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, targetUserId, roomId, msg);
  1984. if (resultInfo.isSuccess()) {
  1985. return true;
  1986. } else {
  1987. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  1988. }
  1989. }
  1990. @Override
  1991. @Transactional(rollbackFor = Exception.class)
  1992. public Boolean approveUpgradeRole(String roomId, String ticket) throws Exception {
  1993. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  1994. CheckUtils.checkArgument(ticket != null, "ticket must't be null");
  1995. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  1996. SysUser authUser = sysUserFeignService.queryUserInfo();
  1997. String userId = authUser.getId().toString();
  1998. UpgradeRoleTaskInfo taskInfo = (UpgradeRoleTaskInfo) scheduleManager.executeTask(ticket);
  1999. log.info("approveUpgradeRole roomId = {}, task={}", roomId, taskInfo);
  2000. RoomMember targetUser = roomMemberDao.findByRidAndUid(roomId, userId);
  2001. if (targetUser == null) {
  2002. throw new ApiException(ErrorEnum.ERR_USER_NOT_EXIST_IN_ROOM);
  2003. }
  2004. if (!taskInfo.getTargetUserId().equals(userId)) {
  2005. throw new ApiException(ErrorEnum.ERR_APPLY_TICKET_INVALID);
  2006. }
  2007. checkOverMax(roomId, targetUser, taskInfo.getRole().getValue());
  2008. roomMemberDao.updateRoleByRidAndUid(roomId, userId, taskInfo.getRole().getValue());
  2009. UpgradeRoleMessage msg = new UpgradeRoleMessage(ActionEnum.Approve.ordinal());
  2010. msg.setOpUserName(authUser.getUsername());
  2011. msg.setOpUserId(userId);
  2012. msg.setRole(taskInfo.getRole().getValue());
  2013. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, taskInfo.getApplyUserId(), roomId, msg);
  2014. if (!resultInfo.isSuccess()) {
  2015. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  2016. }
  2017. RoleChangedMessage rcMsg = new RoleChangedMessage(userId);
  2018. List<RoleChangedMessage.ChangedUser> changedUserList = new ArrayList<>();
  2019. RoleChangedMessage.ChangedUser user = new RoleChangedMessage.ChangedUser(userId, taskInfo.getRole().getValue());
  2020. user.setUserName(authUser.getUsername());
  2021. changedUserList.add(user);
  2022. rcMsg.setUsers(changedUserList);
  2023. imHelper.publishMessage(userId, roomId, rcMsg, 1);
  2024. return true;
  2025. }
  2026. @Override
  2027. @Transactional(rollbackFor = Exception.class)
  2028. public Boolean rejectUpgradeRole(String roomId, String ticket) throws Exception {
  2029. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  2030. CheckUtils.checkArgument(ticket != null, "ticket must't be null");
  2031. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  2032. SysUser authUser = sysUserFeignService.queryUserInfo();
  2033. String userId = authUser.getId().toString();
  2034. UpgradeRoleTaskInfo taskInfo = (UpgradeRoleTaskInfo) scheduleManager.executeTask(ticket);
  2035. UpgradeRoleMessage msg = new UpgradeRoleMessage(ActionEnum.Reject.ordinal());
  2036. msg.setOpUserName(authUser.getUsername());
  2037. msg.setOpUserId(userId);
  2038. msg.setRole(taskInfo.getRole().getValue());
  2039. IMApiResultInfo resultInfo = imHelper.publishMessage(userId, taskInfo.getApplyUserId(), roomId, msg);
  2040. if (resultInfo.isSuccess()) {
  2041. return true;
  2042. } else {
  2043. throw new ApiException(ErrorEnum.ERR_MESSAGE_ERROR, resultInfo.getErrorMessage());
  2044. }
  2045. }
  2046. @Override
  2047. @Transactional(rollbackFor = Exception.class)
  2048. public Boolean changeRole(String roomId, String targetUserId, int targetRole) throws Exception {
  2049. CheckUtils.checkArgument(roomId != null, "roomId must't be null");
  2050. CheckUtils.checkArgument(targetUserId != null, "userId must't be null");
  2051. CheckUtils.checkArgument(roomDao.existsByRid(roomId), "room not exist");
  2052. CheckUtils.checkArgument(RoleEnum.getEnumByValue(targetRole).equals(RoleTeacher), "only set to teacher");
  2053. CheckUtils.checkArgument(roomMemberDao.existsByRidAndUid(roomId, targetUserId), "room member not exist");
  2054. SysUser authUser = sysUserFeignService.queryUserInfo();
  2055. String userId = authUser.getId().toString();
  2056. RoomMember targetUser = roomMemberDao.findByRidAndUid(roomId, targetUserId);
  2057. if (targetUser == null) {
  2058. throw new ApiException(ErrorEnum.ERR_USER_NOT_EXIST_IN_ROOM);
  2059. } else {
  2060. if (!RoleEnum.getEnumByValue(targetUser.getRole()).equals(RoleStudent)) {
  2061. log.error("change role error: targetUserId={}, targetRole = {}", targetUser, RoleEnum.getEnumByValue(targetRole));
  2062. throw new ApiException(ErrorEnum.ERR_CHANGE_ROLE);
  2063. }
  2064. }
  2065. log.info("changeRole: roomId={}, targetUserId={}", roomId, targetUserId);
  2066. List<RoleChangedMessage.ChangedUser> changedUserList = new ArrayList<>();
  2067. RoleChangedMessage msg = new RoleChangedMessage(userId);
  2068. List<RoomMember> teachers = roomMemberDao.findByRidAndRole(roomId, RoleTeacher.getValue());
  2069. if (!teachers.isEmpty()) {
  2070. roomMemberDao.updateRoleByRidAndUid(roomId, teachers.get(0).getUid(), RoleStudent.getValue());
  2071. RoleChangedMessage.ChangedUser user = new RoleChangedMessage.ChangedUser(teachers.get(0).getUid(), RoleStudent.getValue());
  2072. UserInfo userInfo = userDao.findByUid(teachers.get(0).getUid());
  2073. if (userInfo != null) {
  2074. user.setUserName(userInfo.getName());
  2075. }
  2076. changedUserList.add(user);
  2077. } else {
  2078. log.info("change directly cause no teacher exist in room, roomId={}", roomId);
  2079. }
  2080. roomMemberDao.updateRoleByRidAndUid(roomId, targetUserId, targetRole);
  2081. RoleChangedMessage.ChangedUser user = new RoleChangedMessage.ChangedUser(targetUserId, targetRole);
  2082. UserInfo userInfo = userDao.findByUid(targetUserId);
  2083. if (userInfo != null) {
  2084. user.setUserName(userInfo.getName());
  2085. }
  2086. changedUserList.add(user);
  2087. msg.setUsers(changedUserList);
  2088. imHelper.publishMessage(userId, roomId, msg, 1);
  2089. String display = "display://type=1?userId=" + targetUserId + "?uri=";
  2090. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  2091. String roomServiceProviter = getRoomServiceProvider(roomId);
  2092. roomDao.updateDisplayByRid(roomId, display);
  2093. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProviter)) {
  2094. sendDisplayMessage(display, roomMember);
  2095. } else {
  2096. DisplayMessage displayMessage = new DisplayMessage(display);
  2097. imHelper.publishMessage(userId, roomId, displayMessage, 1);
  2098. }
  2099. log.info("changeRole, display changed: roomId={}, {}, targetUserId={}", roomId, display, targetUserId);
  2100. return true;
  2101. }
  2102. @Override
  2103. @Transactional(rollbackFor = Exception.class)
  2104. public Boolean memberOnlineStatus(List<ReqMemberOnlineStatus> statusList, String nonce, String timestamp, String signature) throws Exception {
  2105. String sign = imProperties.getSecret() + nonce + timestamp;
  2106. String signSHA1 = CodeUtil.hexSHA1(sign);
  2107. if (!signSHA1.equals(signature)) {
  2108. log.info("memberOnlineStatus signature error");
  2109. return true;
  2110. }
  2111. for (ReqMemberOnlineStatus status : statusList) {
  2112. int s = Integer.parseInt(status.getStatus());
  2113. String userId = status.getUserId();
  2114. log.info("memberOnlineStatus, userId={}, status={}", userId, status);
  2115. //1:offline 离线; 0: online 在线
  2116. if (s == 1) {
  2117. List<RoomMember> members = roomMemberDao.findByUid(userId);
  2118. if (!members.isEmpty()) {
  2119. scheduleManager.userIMOffline(userId);
  2120. }
  2121. } else if (s == 0) {
  2122. scheduleManager.userIMOnline(userId);
  2123. }
  2124. }
  2125. return true;
  2126. }
  2127. @Override
  2128. @Transactional(rollbackFor = Exception.class)
  2129. public void userIMOfflineKick(String userId) {
  2130. List<RoomMember> members = roomMemberDao.findByUid(userId);
  2131. // 查询课程信息
  2132. List<Long> collect = members.stream()
  2133. .map(x -> x.getRid().substring(1))
  2134. .map(Long::valueOf).distinct().collect(Collectors.toList());
  2135. Map<String, String> serviceProviderMap = Maps.newHashMap();
  2136. if (CollectionUtils.isNotEmpty(collect)) {
  2137. serviceProviderMap = courseScheduleDao.findByCourseScheduleIds(collect).stream()
  2138. .collect(Collectors.toMap(x -> x.getId().toString(), CourseSchedule::getServiceProvider, (o, n) -> n));
  2139. }
  2140. for (RoomMember member : members) {
  2141. int userRole = member.getRole();
  2142. log.info("userIMOfflineKick: roomId={}, {}, role={}", member.getRid(), userId, RoleEnum.getEnumByValue(userRole));
  2143. try {
  2144. if (userRole == RoleTeacher.getValue() || userRole == RoleEnum.RoleAssistant.getValue()) {
  2145. Room room = roomDao.findByRid(member.getRid());
  2146. if (room == null) {
  2147. break;
  2148. }
  2149. if (isUserDisplay(room, member.getUid())) {
  2150. updateDisplay(member.getRid(), member.getUid(), "", 0);
  2151. log.info("memberOnlineStatus offline: roomId={}, {}", member.getRid(), member.getUid());
  2152. }
  2153. }
  2154. if (roomMemberDao.countByRid(member.getRid()) == 1) {
  2155. // 群组当前人数为1时,解散群组
  2156. this.dismissImGroup(member.getUid(), member.getRid(),
  2157. serviceProviderMap.getOrDefault(member.getRid().substring(1), "rongCloud"));
  2158. roomMemberDao.deleteUserByRidAndUid(member.getRid(), member.getUid());
  2159. roomDao.deleteByRid(member.getRid());
  2160. deleteWhiteboardByUser(member.getRid(), member.getUid());
  2161. log.info("dismiss the room: {},userId: {}", member.getRid(), userId);
  2162. } else {
  2163. roomMemberDao.deleteUserByRidAndUid(member.getRid(), member.getUid());
  2164. MemberChangedMessage msg = new MemberChangedMessage(MemberChangedMessage.Action_Leave, member.getUid(), userRole);
  2165. msg.setUserName(member.getName());
  2166. Integer firstCourseId = Integer.parseInt(member.getRid().substring(1));
  2167. CourseSchedule courseSchedule = courseScheduleDao.get(firstCourseId.longValue());
  2168. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(courseSchedule.getServiceProvider())) {
  2169. sendJoinLeaveMessage(member, MemberChangedMessage.Action_Leave);
  2170. } else {
  2171. imHelper.publishMessage(member.getUid(), member.getRid(), msg);
  2172. }
  2173. }
  2174. userDao.deleteByUid(member.getUid());
  2175. } catch (Exception e) {
  2176. log.error("userIMOfflineKick error: userId={}", userId);
  2177. }
  2178. }
  2179. }
  2180. @Override
  2181. @Transactional(rollbackFor = Exception.class)
  2182. public void sendImPlayMidiMessage(PlayMidiMessageData playMidiMessageData) throws Exception {
  2183. SysUser sysUser = sysUserFeignService.queryUserInfo();
  2184. if (sysUser == null) {
  2185. throw new BizException("用户信息获取失败");
  2186. }
  2187. String content = playMidiMessageData.getContent();
  2188. String roomId = playMidiMessageData.getRoomId();
  2189. CustomMessage customMessage = JSONObject.parseObject(content, CustomMessage.class);
  2190. String userId = sysUser.getId().toString();
  2191. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, userId);
  2192. // 获取RTC服务提供方
  2193. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(getRoomServiceProvider(roomId));
  2194. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(pluginService.pluginName())) {
  2195. // 腾讯云RTC服务
  2196. RTCRoomMessage.MessageContent messageContent = RTCRoomMessage.MessageContent
  2197. .builder()
  2198. .enable(customMessage.getEnable())
  2199. .rate(customMessage.getRate())
  2200. .customType(customMessage.getCustomType())
  2201. .userId(customMessage.getUserId())
  2202. .playVolume(customMessage.getPlayVolume())
  2203. .sendUserInfo(getSendUser(roomMember.getUid(), RoleEnum.getEnumByValue(roomMember.getRole())))
  2204. .build();
  2205. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  2206. .objectName(RTCRoomMessage.PLAY_MIDI_MESSAGE)
  2207. .content(messageContent)
  2208. .toChatRoomId(roomMember.getRid())
  2209. .fromUserId(roomMember.getUid())
  2210. .isIncludeSender(1)
  2211. .isPersisted(1)
  2212. .build();
  2213. pluginService.sendChatRoomMessage(roomMessage);
  2214. } else {
  2215. MetronomeMessageMessage displayMessage = new MetronomeMessageMessage(customMessage);
  2216. imHelper.publishMessage(userId, roomId, displayMessage, 1);
  2217. }
  2218. //记录节拍器消息
  2219. courseScheduleStudentPaymentDao.adjustPlayMidi(Long.parseLong(roomId.substring(1)), playMidiMessageData.getUserId(), content);
  2220. }
  2221. @Override
  2222. @Transactional(rollbackFor = Exception.class)
  2223. public void pushDownloadMusicScoreMsg(MusicScoreData musicScoreData) throws Exception {
  2224. SysUser authUser = sysUserFeignService.queryUserInfo();
  2225. String roomId = musicScoreData.getRoomId();
  2226. Long courseScheduleId = Long.parseLong(roomId.substring(1));
  2227. List<CourseScheduleStudentMusicScore> scheduleStudentMusicScores =
  2228. courseScheduleStudentMusicScoreDao.queryByScoreIdAndCourseId(musicScoreData.getMusicScoreAccompanimentId(),
  2229. courseScheduleId, null, null, 0);
  2230. SysMusicScoreAccompaniment accompaniment = sysMusicScoreAccompanimentDao.get(musicScoreData.getMusicScoreAccompanimentId());
  2231. if (scheduleStudentMusicScores.size() == 0) {
  2232. //第一次下载,生成数据
  2233. List<CourseScheduleStudentPayment> courseScheduleStudentPayments = courseScheduleStudentPaymentDao.findByCourseSchedule(courseScheduleId);
  2234. Set<Integer> studentIds = courseScheduleStudentPayments.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
  2235. studentIds.forEach(e -> {
  2236. CourseScheduleStudentMusicScore musicScore = new CourseScheduleStudentMusicScore();
  2237. musicScore.setMusicScoreAccompanimentId(accompaniment.getId());
  2238. musicScore.setSpeed(accompaniment.getSpeed());
  2239. musicScore.setCourseScheduleId(courseScheduleId);
  2240. musicScore.setUserId(e);
  2241. scheduleStudentMusicScores.add(musicScore);
  2242. });
  2243. CourseScheduleStudentMusicScore musicScore = new CourseScheduleStudentMusicScore();
  2244. musicScore.setMusicScoreAccompanimentId(accompaniment.getId());
  2245. musicScore.setSpeed(accompaniment.getSpeed());
  2246. musicScore.setCourseScheduleId(courseScheduleId);
  2247. musicScore.setUserId(authUser.getId());
  2248. musicScore.setUserType(1);
  2249. scheduleStudentMusicScores.add(musicScore);
  2250. courseScheduleStudentMusicScoreDao.batchInsert(scheduleStudentMusicScores);
  2251. }
  2252. MusicScoreMessage musicScoreMessage = JSON.parseObject(JSON.toJSONString(accompaniment), MusicScoreMessage.class);
  2253. // 发送消息
  2254. String serviceProvider = getRoomServiceProvider(musicScoreData.getRoomId());
  2255. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(serviceProvider)) {
  2256. RTCRoomPluginService pluginService = rtcRoomPluginContext.getPluginService(serviceProvider);
  2257. // 腾讯消息推送
  2258. RTCRoomMessage.MessageContent messageContent = RTCRoomMessage.MessageContent
  2259. .builder()
  2260. .url(musicScoreMessage.getUrl())
  2261. .mp3Url(musicScoreMessage.getMp3Url())
  2262. .songId(String.valueOf(musicScoreMessage.getId()))
  2263. .speed(musicScoreMessage.getSpeed())
  2264. .sendUserInfo(RTCRoomMessage.MessageUser.builder()
  2265. .sendUserId(String.valueOf(authUser.getId()))
  2266. .sendUserName(authUser.getUsername())
  2267. .avatarUrl(authUser.getAvatar())
  2268. .build())
  2269. .build();
  2270. RTCRoomMessage roomMessage = RTCRoomMessage.builder()
  2271. .objectName(RTCRoomMessage.MUSIC_SCORE_MESSAGE)
  2272. .content(messageContent)
  2273. .toChatRoomId(roomId)
  2274. .fromUserId(String.valueOf(authUser.getId()))
  2275. .isIncludeSender(1)
  2276. .isPersisted(1)
  2277. .build();
  2278. // 发送消息
  2279. pluginService.sendChatRoomMessage(roomMessage);
  2280. } else {
  2281. // 融云消息推送
  2282. MusicScoreDownloadMessageMessage msg = new MusicScoreDownloadMessageMessage(musicScoreMessage);
  2283. imHelper.publishMessage(authUser.getId().toString(), roomId, msg, 0);
  2284. }
  2285. }
  2286. @Override
  2287. @Transactional(rollbackFor = Exception.class)
  2288. public void pushDownloadExamSongMsg(String roomId, Integer examSongId) throws Exception {
  2289. SysUser authUser = sysUserFeignService.queryUserInfo();
  2290. SysExamSong sysExamSong = sysExamSongDao.get(examSongId);
  2291. if (sysExamSong == null) {
  2292. throw new BizException("曲目信息不存在");
  2293. }
  2294. //学员曲目下载状态改为未下载
  2295. ExamSongDownloadData json = new ExamSongDownloadData();
  2296. json.setExamSongName(sysExamSong.getName());
  2297. json.setUrl(sysExamSong.getUrl());
  2298. json.setStatus(0);
  2299. json.setExamSongId(examSongId);
  2300. courseScheduleStudentPaymentDao.adjustExamSong(Long.parseLong(roomId.substring(1)), null, JSON.toJSONString(json));
  2301. ExamSongMessage examSongMessage = new ExamSongMessage();
  2302. examSongMessage.setExamSongName(sysExamSong.getName());
  2303. examSongMessage.setUrl(sysExamSong.getUrl());
  2304. examSongMessage.setExamSongId(examSongId);
  2305. ExamSongDownloadMessageMessage msg = new ExamSongDownloadMessageMessage(examSongMessage);
  2306. imHelper.publishMessage(authUser.getId().toString(), roomId, msg, 0);
  2307. }
  2308. @Override
  2309. public List<RongyunBasicUserDto> queryNoJoinStu(String roomId) {
  2310. return courseScheduleStudentPaymentDao.queryNoJoinStu(roomId, roomId.substring(1));
  2311. }
  2312. @Override
  2313. @Transactional(rollbackFor = Exception.class)
  2314. public void adjustMusicScore(MusicScoreData musicScoreData) throws Exception {
  2315. SysUser authUser = sysUserFeignService.queryUserInfo();
  2316. Integer studentId = authUser.getId();
  2317. String roomId = musicScoreData.getRoomId();
  2318. Long scheduleId = Long.parseLong(roomId.substring(1));
  2319. Integer accompanimentId = musicScoreData.getMusicScoreAccompanimentId();
  2320. List<CourseScheduleStudentMusicScore> studentMusicScores = courseScheduleStudentMusicScoreDao.queryByScoreIdAndCourseId(accompanimentId, scheduleId, studentId, null, null);
  2321. if (accompanimentId != null) {
  2322. SysMusicScoreAccompaniment accompaniment = sysMusicScoreAccompanimentDao.get(accompanimentId);
  2323. if (accompaniment == null) {
  2324. throw new BizException("曲目信息不存在");
  2325. }
  2326. //修改下载状态
  2327. if (studentMusicScores == null || studentMusicScores.size() == 0) {
  2328. throw new BizException("学员不存在此下载曲目");
  2329. }
  2330. CourseScheduleStudentMusicScore studentMusicScore = studentMusicScores.get(0);
  2331. studentMusicScore.setDownStatus(musicScoreData.getStatus());
  2332. courseScheduleStudentMusicScoreDao.update(studentMusicScore);
  2333. }
  2334. //给老师发送学员曲目下载状态
  2335. CourseSchedule courseSchedule = courseScheduleDao.get(scheduleId);
  2336. MusicScoreDownloadStatusMessage statusMessage = new MusicScoreDownloadStatusMessage(studentId, studentMusicScores);
  2337. imHelper.publishMessage(studentId.toString(), courseSchedule.getActualTeacherId().toString(), roomId, statusMessage);
  2338. }
  2339. @Override
  2340. @Transactional(rollbackFor = Exception.class)
  2341. public void adjustExamSong(String roomId, Integer status, Integer examSongId) throws Exception {
  2342. if (roomId == null || status == null || examSongId == null) {
  2343. throw new BizException("参数校验失败");
  2344. }
  2345. SysUser authUser = sysUserFeignService.queryUserInfo();
  2346. long scheduleId = Long.parseLong(roomId.substring(1));
  2347. SysExamSong sysExamSong = sysExamSongDao.get(examSongId);
  2348. if (sysExamSong == null) {
  2349. throw new BizException("曲目信息不存在");
  2350. }
  2351. ExamSongDownloadData msg;
  2352. String examJson = courseScheduleStudentPaymentDao.getExamJsonByCourseIdAndUserId(scheduleId, authUser.getId());
  2353. if (StringUtils.isEmpty(examJson)) {
  2354. msg = new ExamSongDownloadData();
  2355. msg.setExamSongName(sysExamSong.getName());
  2356. msg.setUrl(sysExamSong.getUrl());
  2357. msg.setStatus(status);
  2358. msg.setExamSongId(examSongId);
  2359. } else {
  2360. msg = JSON.parseObject(examJson, ExamSongDownloadData.class);
  2361. msg.setStatus(status);
  2362. }
  2363. courseScheduleStudentPaymentDao.adjustExamSong(scheduleId, authUser.getId(), JSON.toJSONString(msg));
  2364. //给老师发送学员曲目下载状态
  2365. CourseSchedule courseSchedule = courseScheduleDao.get(scheduleId);
  2366. ExamSongDownloadStatusMessage deviceResourceMessage = new ExamSongDownloadStatusMessage(status, authUser.getId(), examSongId);
  2367. imHelper.publishMessage(authUser.getId().toString(), courseSchedule.getActualTeacherId().toString(), roomId, deviceResourceMessage);
  2368. }
  2369. public void updateDisplay(String roomId, String senderId, String display, Integer isIncludeSender) throws Exception {
  2370. roomDao.updateDisplayByRid(roomId, display);
  2371. RoomMember roomMember = roomMemberDao.findByRidAndUid(roomId, senderId);
  2372. String roomServiceProvider = getRoomServiceProvider(roomId);
  2373. if (TencentCloudRTCPlugin.PLUGIN_NAME.equals(roomServiceProvider)) {
  2374. sendDisplayMessage(display, roomMember);
  2375. } else {
  2376. DisplayMessage displayMessage = new DisplayMessage(display);
  2377. imHelper.publishMessage(senderId, roomId, displayMessage, isIncludeSender);
  2378. }
  2379. }
  2380. public boolean isUserDisplay(Room room, String userId) {
  2381. boolean result = false;
  2382. if (!room.getDisplay().isEmpty() && room.getDisplay().contains("userId=" + userId)) {
  2383. if (room.getDisplay().contains("type=0") || room.getDisplay().contains("type=1") || room.getDisplay().contains("type=3")) {
  2384. result = true;
  2385. }
  2386. }
  2387. return result;
  2388. }
  2389. }