RoomServiceImpl.java 121 KB

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