index.js 14 KB

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