index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import { ROLES, CODEMEG, EVENT, FROMTYPE } from "../../enum/index.js";
  2. import { getCurrentUser, updateUser, removeRoomAllUsers, getAllRoomUsers, updateRoomUser, removeRoomUser } from "../../service/userService.js";
  3. // import { watchRoomService } from "../../service/watchRoomService.js";
  4. import { setRoomConfig, getRoomConfig, updateRoomConfigByKey, isRoomMaster } from "../../service/roomConfigService.js";
  5. import { RoomAssistant } from "./assistant.js";
  6. import { Notify } from "./notify.js";
  7. import { BasicController } from "../basicController.js";
  8. export class RoomController extends BasicController {
  9. constructor(...args) {
  10. super(...args);
  11. this.roomAssistant = new RoomAssistant(this.socket, this.redisCli, this);
  12. this.notify = new Notify(this.socket, this.redisCli, this);
  13. this.roomId = null;
  14. this.sessionId = null;
  15. this.userId = null;
  16. this.roomConfigId = null;
  17. this.debugger = true;
  18. this.user = {
  19. sig: null,
  20. roomId: null,
  21. userId: null,
  22. sceneNum: null,
  23. isClient: null,
  24. avatar: "",
  25. role: null,
  26. userLimitNum: null,
  27. sceneNumber: null,
  28. order: 2,
  29. from: null,
  30. assistantId: null,
  31. onlineStatus: 0,
  32. voiceStatus: 0,
  33. enableTalk: null,
  34. oid: null, // openid
  35. };
  36. }
  37. // 以小程序user信息作为主要信息
  38. async currentUser() {
  39. const data = await getCurrentUser(this.userId, FROMTYPE.MiniAPP);
  40. const user = data ? JSON.parse(data) : this.user;
  41. return user;
  42. }
  43. async run() {
  44. this.logger.info("socket conetcted has start!");
  45. try {
  46. await this.init();
  47. this.initBaseAction();
  48. this.roomMasterAutoRejoin();
  49. this.roomAssistant.watchRoomExpired();
  50. // setInterval(async () => {
  51. // if ([FROMTYPE.Bridge].includes(Number(this.user.from))) {
  52. // const AllRoomUsers = await getAllRoomUsers(this.roomId);
  53. // this.socket.broadcast.to(this.roomId).emit(EVENT.roomStatus, {
  54. // roomsPerson: AllRoomUsers,
  55. // });
  56. // console.log("定时测试", this.roomId);
  57. // }
  58. // }, 10000);
  59. } catch (error) {
  60. this.logger.error("roomController::run::error", error);
  61. }
  62. }
  63. async init() {
  64. let user = this.socket.handshake.query;
  65. this.logger.info("init-user-query:", this.socket.handshake.query);
  66. if (user) {
  67. this.user = Object.assign({}, user);
  68. this.user.sig = this.getSig(this.user.userId);
  69. const oneSceneNum = this.user.sceneNumber || this.user.sceneNum;
  70. const { userId, roomId } = this.user;
  71. await this.initParams(userId, roomId, oneSceneNum);
  72. let order;
  73. switch (this.user.role) {
  74. case "leader":
  75. order = 0;
  76. break;
  77. case "assistant":
  78. order = 1;
  79. break;
  80. case "customer":
  81. order = 2;
  82. break;
  83. default:
  84. order = 2;
  85. break;
  86. }
  87. const userObj = { ...this.user, onlineStatus: 1, isConnected: true, order };
  88. const assistantId = await this.roomAssistant.getRoomAssistant(this.roomId);
  89. if (!this.isHoster(this.user.role)) {
  90. console.log("assistantId", assistantId);
  91. console.log("this.userId", this.user.userId);
  92. this.logger.info("默认变更条件:" + (assistantId && Number(this.user.userId) !== Number(assistantId)));
  93. if (assistantId && Number(this.user.userId) !== Number(assistantId)) {
  94. this.logger.info("已存在默认助手变更:" + "room助手ID: " + assistantId + " userId: " + this.user.userId);
  95. userObj.role = "customer";
  96. }
  97. }
  98. // if (assistantId && Number(this.userId) !== Number(assistantId) && !this.isHoster(this.user.role)) {
  99. // userObj.role = "customer";
  100. // }
  101. this.logger.info("update-user-info:", userObj);
  102. updateUser(this.userId, userObj);
  103. // 将更新同步一份到process
  104. this.user = userObj;
  105. // this.sysUsers.push(this.user);
  106. // 只有来源于小程序用户信息才记录到redis
  107. if (this.isHoster(this.user.role)) {
  108. if ([FROMTYPE.MiniAPP].includes(Number(this.user.from))) {
  109. const roomConfig = getRoomConfig(this.roomId);
  110. const checkoutMaster = await isRoomMaster(this.roomId, this.userId);
  111. const isNoExistMaster = "masterId" in roomConfig;
  112. // console.log("checkoutMaster-isNoExistMaster", checkoutMaster, !isNoExistMaster);
  113. if (checkoutMaster || !isNoExistMaster) {
  114. console.log("房主进入记录信息::: checkoutMaster: %s, isNoExistMaster: %s ,roomId %s", checkoutMaster, !isNoExistMaster, this.roomId);
  115. const roomConfig = {
  116. masterId: this.userId,
  117. userLimitNum: this.user.userLimitNum,
  118. enableTalk: this.user.enableTalk === "true" ? true : false,
  119. };
  120. console.log("roomConfig", roomConfig);
  121. // console.log("roomConfig", roomConfig);
  122. await setRoomConfig(this.roomId, roomConfig);
  123. }
  124. }
  125. }
  126. // 加入
  127. console.log("roomId", this.roomId);
  128. this.socket.join(this.roomId);
  129. } else {
  130. this.logger.info("user-query-不存在 :", this.socket.handshake.query);
  131. this.socket.disconnect();
  132. }
  133. }
  134. async initParams(userId, roomId, oneSceneNum) {
  135. this.userId = `user:${userId}`;
  136. this.syncId = `sync:${oneSceneNum}:${userId}`;
  137. this.sessionId = `session:${oneSceneNum}:${userId}`;
  138. const uRoomId = await this.roomAssistant.prepearRoom(this.sessionId, roomId);
  139. // this.roomId = `room:${uRoomId}_${oneSceneNum}`;
  140. this.roomId = `room:${oneSceneNum}:${uRoomId}`;
  141. this.user.roomId = uRoomId;
  142. this.roomConfigId = `config:${this.roomId}`;
  143. return Promise.resolve(true);
  144. }
  145. initBaseAction() {
  146. // 通知 baseView 减少大量通知
  147. this.socket.on(EVENT.webSyncAction, (data) => {
  148. // socket.broadcast.to(roomUniqueId).emit(EVENT.webSyncAction, data);
  149. try {
  150. if ([FROMTYPE.base].includes(Number(this.user.from))) {
  151. this.socket.broadcast.to(this.roomId).emit(EVENT.webSyncAction, data);
  152. }
  153. } catch (error) {
  154. this.logger.error("roomController::EVENT.webSyncAction", error);
  155. }
  156. });
  157. // 转发action
  158. this.socket.on(EVENT.action, (data) => {
  159. try {
  160. this.logger.debug("room-action", this.roomId, this.socket.rooms.has(this.roomId), JSON.stringify(data));
  161. if (this.socket.rooms.has(this.roomId)) {
  162. this.socket.broadcast.to(this.roomId).emit(EVENT.action, data);
  163. } else {
  164. this.logger.error("action 事件不在房间内", this.user);
  165. }
  166. } catch (error) {
  167. this.logger.error("roomController::EVENT.action", error);
  168. }
  169. });
  170. this.socket.on(EVENT.startCall, async () => {
  171. const user = await this.currentUser();
  172. this.roomAssistant.startCall(this.roomId, this.userId, user);
  173. // console.log("startCall-from", this.user.from);
  174. if (this.isHoster(this.user.role)) {
  175. // 以startCall做为真正的进入房间
  176. await updateRoomConfigByKey(this.roomId, "isStart", true);
  177. }
  178. });
  179. this.socket.on(EVENT.stopCall, () => {
  180. setTimeout(() => {
  181. console.log("EVENT.stopCall-delay");
  182. this.roomAssistant.stopCall(this.roomId, this.userId, this.user);
  183. if (this.isHoster(this.user.role)) {
  184. // 以stopCall断开做为真正的退出房间
  185. this.roomAssistant.destoryRoom(this.sessionId, this.roomConfigId);
  186. }
  187. }, 1000);
  188. });
  189. this.socket.on(EVENT.changeRoomEnableTalk, async (data) => {
  190. // this._roomsConfig[roomId].enableTalk = data;
  191. try {
  192. const roomConfig = await getRoomConfig(this.roomId);
  193. roomConfig.enableTalk = data;
  194. await setRoomConfig(this.roomId, roomConfig);
  195. this.logger.info("changeRoomEnableTalk", JSON.stringify(data));
  196. this.socket.broadcast.to(this.roomId).emit(EVENT.changeRoomEnableTalk, roomConfig);
  197. } catch (error) {
  198. this.logger.error("event:changeRoomEnableTalk", error);
  199. }
  200. });
  201. this.socket.on(EVENT.changeOnlineStatus, async (data) => {
  202. try {
  203. const user = await this.currentUser();
  204. user.onlineStatus = Number(data.status);
  205. await updateRoomUser(this.roomId, this.userId, user);
  206. this.user = user;
  207. //更新一份
  208. let actionName = Number(user.onlineStatus) === 1 ? "inRoom" : "leaveRoom";
  209. this.logger.info("changeOnlineStatus", JSON.stringify(user));
  210. const AllRoomUsers = await getAllRoomUsers(this.roomId);
  211. this.socket.broadcast.to(this.roomId).emit(EVENT.roomPersonChange, {
  212. roomsPerson: AllRoomUsers,
  213. actionName,
  214. user: user,
  215. });
  216. } catch (error) {
  217. this.logger.error("event:changeOnlineStatus", error);
  218. }
  219. });
  220. /**
  221. * 踢人管理
  222. */
  223. this.socket.on(EVENT.kickUser, async ({ data, from }) => {
  224. // 要前端断线才可以踢人
  225. try {
  226. const userId = `user:${data.userId}`;
  227. const roomId = `room:${data.sceneNumber}:${data.roomId}`;
  228. const currentUser = await getCurrentUser(userId, FROMTYPE.MiniAPP);
  229. const user = JSON.parse(currentUser);
  230. // 被踢人不能是hoster
  231. console.log("user", JSON.stringify(user));
  232. if (user && !this.isHoster(user.role)) {
  233. console.log("currentUser.role", user.role);
  234. // 如果踢人后 如何通知?
  235. this.socket.broadcast.to(roomId).emit(EVENT.beKicked, data);
  236. const isKick = await this.roomAssistant.kickPersion(roomId, userId);
  237. if (isKick) {
  238. const AllRoomUsers = await getAllRoomUsers(roomId);
  239. console.log("kickUser-AllRoomUsers", AllRoomUsers.length);
  240. this.logger.info("kickUser", currentUser, userId, roomId);
  241. // 通知管理
  242. this.socket.emit(EVENT.someOneLeaveRoom, {
  243. user: user,
  244. roomsPerson: AllRoomUsers,
  245. });
  246. // 通知房间人员变动
  247. this.socket.broadcast.to(roomId).emit(EVENT.someOneLeaveRoom, {
  248. user: user,
  249. roomsPerson: AllRoomUsers,
  250. });
  251. }
  252. } else {
  253. const nickname = user.nickname || "";
  254. this.logger.warn(nickname + "是房主,不能被踢!!");
  255. }
  256. } catch (error) {
  257. console.error("error", error);
  258. }
  259. });
  260. /**
  261. * 设置助手
  262. */
  263. this.socket.on("setAssistant", async ({ data, from }) => {
  264. const userId = `user:${data.userId}`;
  265. const roomId = `room:${data.sceneNumber}:${data.roomId}`;
  266. console.log("设置助手", userId, roomId);
  267. this.roomAssistant.setAssistant(roomId, userId, data.cancel);
  268. });
  269. /**
  270. * 设置MIC权
  271. */
  272. this.socket.on("setUserhasMic", async ({ data, from, isAllowMic }) => {
  273. const userId = `user:${data.userId}`;
  274. const roomId = `room:${data.sceneNumber}:${data.roomId}`;
  275. console.log("设置MIC权", userId, roomId, data.isAllowMic);
  276. this.roomAssistant.setMicRight(roomId, userId, data.isAllowMic);
  277. });
  278. if (this.debugger) {
  279. this.socket.onAny((event, data) => {
  280. if (event !== "webSyncAction") {
  281. // console.log(`onAny:get ${event}, data:${JSON.stringify(data)}`);
  282. this.logger.info(`onAny:get ${event}, data:${JSON.stringify(data)}`);
  283. }
  284. });
  285. }
  286. }
  287. async roomMasterAutoRejoin() {
  288. try {
  289. const sessionExist = await this.redisCli.exists(this.sessionId);
  290. const roomConfig = await getRoomConfig(this.roomId);
  291. if (sessionExist > 0 && roomConfig.isStart && roomConfig.isStart === "true") {
  292. const AllRoomUsers = await getAllRoomUsers(this.roomId);
  293. // 房主
  294. if (this.isHoster(this.user.role)) {
  295. console.log("自动接连", this.roomId, this.user.from);
  296. this.socket.join(this.roomId);
  297. this.socket.emit("autoReJoin", {
  298. user: this.user,
  299. roomsPerson: AllRoomUsers,
  300. roomId: this.user.roomId,
  301. });
  302. //TODO someOneInRoom是用来触发语音与更新房间状态
  303. }
  304. //TODO someOneInRoom是用来触发语音与更新房间状态
  305. // setTimeout(() => {
  306. // this.socket.emit("someOneInRoom", {
  307. // user: this.user,
  308. // roomsPerson: AllRoomUsers,
  309. // });
  310. // });
  311. }
  312. } catch (error) {
  313. this.logger.error("room::roomMasterAutoRejoin", error);
  314. }
  315. }
  316. }