index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. 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.issAssistant) === 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. } else {
  125. this.logger.info("user-query-不存在 :", this.socket.handshake.query);
  126. this.socket.disconnect();
  127. }
  128. }
  129. async initParams(userId, roomId, oneSceneNum) {
  130. this.userId = `user:${userId}`;
  131. this.syncId = `sync:${oneSceneNum}:${userId}`;
  132. this.sessionId = `session:${oneSceneNum}:${userId}`;
  133. const uRoomId = await this.roomAssistant.prepearRoom(this.sessionId, roomId);
  134. // this.roomId = `room:${uRoomId}_${oneSceneNum}`;
  135. this.roomId = `room:${oneSceneNum}:${uRoomId}`;
  136. this.user.roomId = uRoomId;
  137. this.roomConfigId = `config:${this.roomId}`;
  138. return Promise.resolve(true);
  139. }
  140. initBaseAction() {
  141. // 通知 baseView 减少大量通知
  142. this.socket.on(EVENT.webSyncAction, (data) => {
  143. // socket.broadcast.to(roomUniqueId).emit(EVENT.webSyncAction, data);
  144. try {
  145. if ([FROMTYPE.base].includes(Number(this.user.from))) {
  146. this.socket.broadcast.to(this.roomId).emit(EVENT.webSyncAction, data);
  147. }
  148. } catch (error) {
  149. this.logger.error("roomController::EVENT.webSyncAction", error);
  150. }
  151. });
  152. // 转发action
  153. this.socket.on(EVENT.action, (data) => {
  154. try {
  155. this.logger.debug("room-action", this.roomId, this.socket.rooms.has(this.roomId), JSON.stringify(data));
  156. if (this.socket.rooms.has(this.roomId)) {
  157. this.socket.broadcast.to(this.roomId).emit(EVENT.action, data);
  158. } else {
  159. this.logger.error("action 事件不在房间内", this.user);
  160. }
  161. } catch (error) {
  162. this.logger.error("roomController::EVENT.action", error);
  163. }
  164. });
  165. this.socket.on(EVENT.startCall, async () => {
  166. const user = await this.currentUser();
  167. this.roomAssistant.startCall(this.roomId, this.userId, user);
  168. // console.log("startCall-from", this.user.from);
  169. if (this.isHoster(this.user.role)) {
  170. // 以startCall做为真正的进入房间
  171. await updateRoomConfigByKey(this.roomId, "isStart", true);
  172. }
  173. });
  174. this.socket.on(EVENT.stopCall, () => {
  175. setTimeout(() => {
  176. console.log("EVENT.stopCall-delay");
  177. this.roomAssistant.stopCall(this.roomId, this.userId, this.user);
  178. if (this.isHoster(this.user.role)) {
  179. // 以stopCall断开做为真正的退出房间
  180. this.roomAssistant.destoryRoom(this.sessionId, this.roomConfigId);
  181. }
  182. }, 1000);
  183. });
  184. this.socket.on(EVENT.changeRoomEnableTalk, async (data) => {
  185. // this._roomsConfig[roomId].enableTalk = data;
  186. try {
  187. const roomConfig = await getRoomConfig(this.roomId);
  188. roomConfig.enableTalk = data;
  189. await setRoomConfig(this.roomId, roomConfig);
  190. this.logger.info("changeRoomEnableTalk", JSON.stringify(data));
  191. this.socket.broadcast.to(this.roomId).emit(EVENT.changeRoomEnableTalk, roomConfig);
  192. } catch (error) {
  193. this.logger.error("event:changeRoomEnableTalk", error);
  194. }
  195. });
  196. this.socket.on(EVENT.changeOnlineStatus, async (data) => {
  197. try {
  198. const user = await this.currentUser();
  199. user.onlineStatus = Number(data.status);
  200. await updateRoomUser(this.roomId, this.userId, user);
  201. this.user = user;
  202. //更新一份
  203. let actionName = Number(user.onlineStatus) === 1 ? "inRoom" : "leaveRoom";
  204. this.logger.info("changeOnlineStatus", JSON.stringify(user));
  205. const AllRoomUsers = await getAllRoomUsers(this.roomId);
  206. this.socket.broadcast.to(this.roomId).emit(EVENT.roomPersonChange, {
  207. roomsPerson: AllRoomUsers,
  208. actionName,
  209. user: user,
  210. });
  211. } catch (error) {
  212. this.logger.error("event:changeOnlineStatus", error);
  213. }
  214. });
  215. /**
  216. * 踢人管理
  217. */
  218. this.socket.on(EVENT.kickUser, async ({ data, from }) => {
  219. // 要前端断线才可以踢人
  220. try {
  221. const userId = `user:${data.userId}`;
  222. const roomId = `room:${data.sceneNumber}:${data.roomId}`;
  223. const currentUser = await getCurrentUser(userId, FROMTYPE.MiniAPP);
  224. const user = JSON.parse(currentUser);
  225. // 被踢人不能是hoster
  226. console.log("user", JSON.stringify(user));
  227. if (user && !this.isHoster(user.role)) {
  228. console.log("currentUser.role", user.role);
  229. // 如果踢人后 如何通知?
  230. this.socket.broadcast.to(roomId).emit(EVENT.beKicked, data);
  231. setTimeout(async () => {
  232. const isKick = await this.roomAssistant.kickPersion(roomId, userId);
  233. if (isKick) {
  234. const AllRoomUsers = await getAllRoomUsers(roomId);
  235. console.log("kickUser-AllRoomUsers", AllRoomUsers.length);
  236. this.logger.info("kickUser", currentUser, userId, roomId);
  237. // 通知管理
  238. this.socket.emit(EVENT.someOneLeaveRoom, {
  239. user: user,
  240. roomsPerson: AllRoomUsers,
  241. });
  242. // 通知房间人员变动
  243. this.socket.broadcast.to(roomId).emit(EVENT.someOneLeaveRoom, {
  244. user: user,
  245. roomsPerson: AllRoomUsers,
  246. });
  247. }
  248. }, 2000);
  249. } else {
  250. const nickname = user.nickname || "";
  251. this.logger.warn(nickname + "是房主,不能被踢!!");
  252. }
  253. } catch (error) {
  254. console.error("error", error);
  255. }
  256. });
  257. /**
  258. * 设置助手
  259. */
  260. this.socket.on("setAssistant", async ({ data, from }) => {
  261. const userId = `user:${data.userId}`;
  262. const roomId = `room:${data.sceneNumber}:${data.roomId}`;
  263. console.log("设置助手", userId, roomId);
  264. this.roomAssistant.setAssistant(roomId, userId, data.cancel);
  265. });
  266. /**
  267. * 设置MIC权
  268. */
  269. this.socket.on("setUserhasMic", async ({ data, from, isAllowMic }) => {
  270. const userId = `user:${data.userId}`;
  271. const roomId = `room:${data.sceneNumber}:${data.roomId}`;
  272. console.log("设置MIC权", userId, roomId, data.isAllowMic);
  273. this.roomAssistant.setMicRight(roomId, userId, data.isAllowMic);
  274. });
  275. if (this.debugger) {
  276. this.socket.onAny((event, data) => {
  277. if (event !== "webSyncAction") {
  278. // console.log(`onAny:get ${event}, data:${JSON.stringify(data)}`);
  279. this.logger.info(`onAny:get ${event}, data:${JSON.stringify(data)}`);
  280. }
  281. });
  282. }
  283. }
  284. async roomMasterAutoRejoin() {
  285. try {
  286. const sessionExist = await this.redisCli.exists(this.sessionId);
  287. const roomConfig = await getRoomConfig(this.roomId);
  288. if (sessionExist > 0 && roomConfig.isStart && roomConfig.isStart === "true") {
  289. const AllRoomUsers = await getAllRoomUsers(this.roomId);
  290. // 房主
  291. if (this.isHoster(this.user.role)) {
  292. console.log("自动接连", this.roomId, this.user.from);
  293. this.socket.join(this.roomId);
  294. this.socket.emit("autoReJoin", {
  295. user: this.user,
  296. roomsPerson: AllRoomUsers,
  297. roomId: this.user.roomId,
  298. });
  299. //TODO someOneInRoom是用来触发语音与更新房间状态
  300. }
  301. //TODO someOneInRoom是用来触发语音与更新房间状态
  302. // setTimeout(() => {
  303. // this.socket.emit("someOneInRoom", {
  304. // user: this.user,
  305. // roomsPerson: AllRoomUsers,
  306. // });
  307. // });
  308. }
  309. } catch (error) {
  310. this.logger.error("room::roomMasterAutoRejoin", error);
  311. }
  312. }
  313. }